Skip to content

Latest commit

 

History

History
126 lines (92 loc) · 1.83 KB

catch-error-name.md

File metadata and controls

126 lines (92 loc) · 1.83 KB

Enforce a specific parameter name in catch clauses

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.

This rule is fixable.

Fail

try {} catch (badName) {}
// `_` is not allowed if it's used
try {} catch (_) {
	console.log(_);
}
promise.catch(badName => {});
promise.then(undefined, badName => {});

Pass

try {} catch (error) {}
promise.catch(error => {});
promise.then(undefined, error => {});
// `_` is allowed when it's not used
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.