sindresorhus/eslint-plugin-unicorn

`custom-error-definition`: Enforce standard error constructors when subclassing (message, options)

Closed

#1,810 opened on May 11, 2022

 (3 comments) (1 reaction) (0 assignees)JavaScript (468 forks)user submission
enhancementhelp wanted

Repository metrics

Stars
 (5,022 stars)
PR merge metrics
 (Avg merge 1d 16h) (399 merged PRs in 30d)

Description

Description

Error#cause was recently added and the native way (Node 16.9+) to set this property is via the options parameter:

new Error('Sup', {
	cause: new Error('Network failed')
})

When subclassing Error, this parameter can be lost or simply use a different format.

This is a companion rule to https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1342

  • that rule: enforce cause when creating Errors
  • this suggestion: enforce cause (and more generally an options object as second parameter) when subclassing errors

Fail

class OutOfBounds extends Error {
	constructor(message) {
		super('Oops: ', message)
	}
}

new OutOfBounds('naw', {cause: new Error('stuff')}) // `cause` lost
class OutOfBounds extends Error {
	constructor(message, details) {
		super(message)
		this.details = details;
	}
}

Pass

class OutOfBounds extends Error {
	constructor(message: string, options: ErrorOptions) {
		super('Oops: ', message, options)
	}
}
class OutOfBounds extends Error {
	constructor(message: string, options: ErrorOptions) {
		super(message, options)
		this.details = options?.details;
	}
}

Contributor guide