sindresorhus/eslint-plugin-unicorn

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

Open

#1,810 opened on May 11, 2022

View on GitHub
 (3 comments) (1 reaction) (0 assignees)JavaScript (5,022 stars) (468 forks)user submission
enhancementhelp wanted

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