Skip to content

Latest commit

 

History

History
114 lines (86 loc) · 1.51 KB

catch-error-name.md

File metadata and controls

114 lines (86 loc) · 1.51 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 error2 = new Error('🦄');

	obj.catch(error3 => {
		// `error3` 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. Default is ^_$.

With ^unicorn$, this would fail:

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

And this would pass:

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