preserve-caught-error
eslint
SuggestionRecommended
eslint.config.js
export default [
{
rules: {
"preserve-caught-error": "error",
},
},
];Disallow losing originally caught error when re-throwing custom errors
// Not using the `cause` option
try {
// ...
} catch (error) {
throw new Error("Something went wrong: " + error.message);
}
// Throwing a new Error with unrelated cause
try {
doSomething();
} catch (err) {
const unrelated = new Error("other");
throw new Error("Something failed", { cause: unrelated });
}
// Caught error is being lost partially due to destructuring
try {
doSomething();
} catch ({ message, ...rest }) {
throw new Error(message);
}
// Cause error is being shadowed by a closer scoped redeclaration.
try {
doSomething();
} catch (error) {
if (whatever) {
const error = anotherError; // This declaration is the problem.
throw new Error("Something went wrong", { cause: error });
}
}try {
// ...
} catch (error) {
throw new Error("Something went wrong", { cause: error });
}
// When the thrown error is not directly related to the caught error.
try {
} catch (error) {
foo = {
bar() {
// This throw is not directly related to the caught error.
throw new Error("Something went wrong");
}
};
}
// No throw inside catch
try {
doSomething();
} catch (e) {
console.error(e);
}
// Ignoring the caught error at the parameter level
// This is valid by default, but this behavior can be changed
// by using the `requireCatchParameter` option discussed below.
try {
doSomething();
} catch {
throw new TypeError("Something went wrong");
}Examples from the ESLint documentation.
preserve-caught-error
eslint
export default [
{
rules: {
"preserve-caught-error": "error",
},
},
];preserve-caught-error
eslint plugin · suspicious
{
"rules": {
"preserve-caught-error": "error"
}
}style/useErrorCause
style · since 2.3.12
{
"linter": {
"rules": {
"style": {
"useErrorCause": "error"
}
}
}
}Require spread operators instead of .apply()
Disallow the use of undeclared variables unless mentioned in /*global */ comments
Disallow confusing multiline expressions
Disallow variable assignments when the value is not used