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.
try {
doSomething();
} catch (ohNoes) {
// …
}
somePromise.catch(e => {})
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);
});
You can set the name
option like this:
"unicorn/catch-error-name": [
"error",
{
"name": "error"
}
]
"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) {
// …
}
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 setting for caughtErrorsIgnorePattern
allows the use of descriptive names instead, for example, fsError
or authError
.