src/content/docs/linter/rules/use-error-cause.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> :::caution This rule is part of the [nursery](/linter/#nursery) group. This means that it is experimental and the behavior can change at any time. ::: ## Summary - Rule available since: `v2.3.12` - Diagnostic Category: [`lint/nursery/useErrorCause`](/reference/diagnostics#diagnostic-category) - This rule doesn't have a fix. - The default severity of this rule is [**information**](/reference/diagnostics#information). - Sources: - Same as [`preserve-caught-error`](https://eslint.org/docs/latest/rules/preserve-caught-error){
"linter": {
"rules": {
"nursery": {
"useErrorCause": "error"
}
}
}
}
Enforce that new Error() is thrown with the original error as cause.
When catching and rethrowing an error, it's recommended to wrap the original error in a new Error object to preserve the original error's stack trace and context. The original error should be passed as the cause property of the new Error object.
This rule enforces that practice, helping to maintain a clear and traceable error propagation chain, which is crucial for effective debugging.
try {
// ...
} catch (err) {
throw new Error(err.message);
}
try {
doSomething();
} catch {
throw new Error("Something went wrong");
}
try {
// ...
} catch ({ message }) {
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 shadows the caught error.
throw new Error("Something went wrong", { cause: error });
}
}
try {
// ...
} catch (err) {
throw new Error("Something went wrong", { cause: err });
}
try {
throw "Not a rethrow, so it's ignored when nested";
} catch (err) {
const fn = () => {
throw new Error("New unrelated error");
}
fn();
}
The following options are available:
requireCatchParameterIf true, the rule will report a diagnostic for a throw statement inside an empty catch {} block, recommending that the error be caught in a parameter.
Default: true
{
"linter": {
"rules": {
"nursery": {
"useErrorCause": {
"options": {
"requireCatchParameter": false
}
}
}
}
}
}
This option is enabled by default, meaning the following code is considered invalid:
try {
doSomething();
} catch {
throw new Error("Something went wrong");
}
To disable this check, you would set the option to false:
try {
doSomething();
} catch {
throw new Error("Something went wrong");
}