An ESLint plugin with rules to report loss of original error cause, when re-throwing errors.
From MDN docs
The cause data property of an Error instance indicates the specific original cause of the error.
It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error.
This property was only added to Node in its 16.9.0
release, before which JavaScript developers used to rely on workarounds like including the cause
error message in the symptom
error message like so:
catch(error) {
// NO LONGER NEEDED ❌
throw new Error(`Failed to perform operation xyz: ${error.message}`);
}
The modern way to do this is by explicitly specifying the cause
error in the symptom
error constructor, essentially chaining the two errors which has been a common pattern in other languages like Java.
catch(error) {
throw new Error(`Failed to perform operation xyz`, {
cause: error // The right way ✅
});
}
Install eslint
and this plugin as dev dependencies.
pnpm add -D eslint eslint-plugin-error-cause
From v8.21.0, eslint announced a new config system. In the new system, .eslintrc*
is no longer used. eslint.config.js
would be the default config file name. In eslint v8
, the legacy system (.eslintrc*) would still be supported, while in eslint v9
, only the new system would be supported.
And from v8.23.0
, eslint CLI starts to look up eslint.config.js
. This plugin only supports the new config system, so if your eslint is >=8.23.0
, you're 100% ready to use the new config system.
You could either use the preset recommended
config exported from this project or enable the rule manually.
This enables no-swallowed-error-cause
rule with a warn
severity level.
import errorCause from "eslint-plugin-error-cause";
import { defineConfig } from "eslint/config";
export default defineConfig([errorCause.configs.recommended]);
This is particularly useful if you want to set a different severity level than warn
.
import errorCause from "eslint-plugin-error-cause";
import { defineConfig } from "eslint/config";
export default defineConfig([
{
plugins: {
"error-cause": errorCause,
},
rules: {
"error-cause/no-swallowed-error-cause": "warn",
},
},
]);
🔧 Automatically fixable by the --fix
CLI option.
Name | Description | 🔧 |
---|---|---|
no-swallowed-error-cause | disallow losing original error cause when re-throwing custom errors. |
🔧 |
Got an idea for a new rule, or found a bug that needs to be fixed?
Its time to file an issue!
Make sure to read CONTRIBUTING.md for more details.
- typescript-eslint playground helps visualize JS and TS ASTs and aid development when writing rules.
- eslint-plugin-exception-handling is a wider scoped exception handling plugin.
eslint-plugin-error-cause
is licensed under the MIT License.