sindresorhus/eslint-plugin-unicorn
View on GitHub`custom-error-definition`: Enforce standard error constructors when subclassing (message, options)
Open
#1,810 opened on May 11, 2022
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
causewhen creating Errors - this suggestion: enforce
cause(and more generally anoptionsobject 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;
}
}