sindresorhus/eslint-plugin-unicorn

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

クローズ

#1,810 opened on 2022/05/11

 (3 件のコメント) (1 件のリアクション) (0 人の担当者)JavaScript (468 件のフォーク)user submission
enhancementhelp wanted

Repository metrics

Stars
 (5,022 個のスター)
PR merge metrics
 (平均マージ 4h 30m) (30d で 26 merged PRs)

説明

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;
	}
}

コントリビューターガイド