Skip to content

Latest commit

ย 

History

History
131 lines (95 loc) ยท 2.31 KB

File metadata and controls

131 lines (95 loc) ยท 2.31 KB

catch-error-name

๐Ÿ“ Enforce a specific parameter name in catch clauses.

๐Ÿ’ผ๐Ÿšซ This rule is enabled in the โœ… recommended config. This rule is disabled in the โ˜‘๏ธ unopinionated config.

๐Ÿ”ง This rule is automatically fixable by the --fix CLI option.

Applies to

  • try/catch clauses handlers
  • promise.catch(โ€ฆ) handlers
  • promise.then(onFulfilled, โ€ฆ) handlers

The desired name is configurable, but defaults to error.

The following names are ignored:

  • _, but only if the error is not used.
  • Descriptive names, for example, fsError or authError.
  • Names matching options.ignore.

Examples

// โŒ
try {} catch (badName) {}

// โœ…
try {} catch (error) {}
// โŒ
promise.catch(badName => {});

// โœ…
promise.catch(error => {});
// โŒ
promise.then(undefined, badName => {});

// โœ…
promise.then(undefined, error => {});
// โŒ
try {} catch (_) {
	console.log(_);
}

// โœ…
try {} catch (_) {
	console.log(foo);
}
// โœ…
// Descriptive name is allowed
try {} catch (fsError) {}
// โœ…
// `error_` is allowed because of shadowed variables
try {} catch (error_) {
	const error = new Error('๐Ÿฆ„');
}

Options

name

Type: string
Default: 'error'

You can set the name option like this:

"unicorn/catch-error-name": [
	"error",
	{
		"name": "exception"
	}
]

ignore

Type: Array<string | RegExp>
Default: []

This option lets you specify a regex pattern for matches to ignore.

When a string is given, it's interpreted as a regular expressions inside a string. Needed for ESLint config in JSON.

"unicorn/catch-error-name": [
	"error",
	{
		"ignore": [
			"^error\\d*$",
			/^ignore/i
		]
	}
]

With ^unicorn$, this would fail:

try {} catch (pony) {}

And this would pass:

try {} catch (unicorn) {}

Tip

In order to avoid shadowing in nested catch clauses, the auto-fix rule appends underscores to the identifier name.