Skip to content

Latest commit

 

History

History
128 lines (98 loc) · 1.86 KB

catch-error-name.md

File metadata and controls

128 lines (98 loc) · 1.86 KB

Enforce a specific parameter name in catch clauses

Applies to both try/catch clauses and promise.catch(...) handlers.

The desired name is configurable, but defaults to error.

This rule is fixable unless the reported code was destructuring an error.

Fail

try {
	doSomething();
} catch (ohNoes) {
	// …
}
somePromise.catch(e => {})

Pass

try {
	doSomething();
} catch (error) {
	// …
}
somePromise.catch(error => {})
try {
	doSomething();
} catch (anyName) { // Nesting of catch clauses disables the rule
	try {
		doSomethingElse();
	} catch (anyOtherName) {
		// ...
	}
}
try {
	doSomething();
} catch (_) {
	// `_` is allowed when the error is not used
	console.log(foo);
}
const handleError = error => {
	const error_ = new Error('🦄');

	obj.catch(error__ => {
		// `error__` is allowed because of shadowed variables
	});
}
somePromise.catch(_ => {
	// `_` is allowed when the error is not used
	console.log(foo);
});

Options

name

You can set the name option like this:

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

caughtErrorsIgnorePattern

"unicorn/catch-error-name": [
	"error",
	{
		"caughtErrorsIgnorePattern": "^_$"
	}
]

This option lets you specify a regex pattern for matches to ignore. The default allows _ and descriptive names like networkError.

With ^unicorn$, this would fail:

try {
	doSomething();
} catch (pony) {
	// …
}

And this would pass:

try {
	doSomething();
} catch (unicorn) {
	// …
}

Tip

In order to avoid shadowing in nested catch clauses the auto-fix rule appends underscores to the identifier name. Since this might be hard to read the default settings for caughtErrorsIgnorePattern allows to use descriptive names instead, e.g. fsError or authError.