Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
fregante opened this issue May 11, 2022 · 3 comments

Comments

@fregante
Copy link
Collaborator

fregante commented May 11, 2022

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 #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;
	}
}
@sindresorhus
Copy link
Owner

Maybe it should be part of custom-error-definition?

@fregante
Copy link
Collaborator Author

fregante commented Jul 6, 2022

Sounds like exactly it!

@sindresorhus sindresorhus changed the title Rule proposal: Enforce standard error constructors when subclassing (message, options) custom-error-definition: Enforce standard error constructors when subclassing (message, options) Jul 6, 2022
@sindresorhus
Copy link
Owner

Accepted

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants