only-throw-error
Disallow throwing non-
Error
values as exceptions.
Extending "plugin:@typescript-eslint/recommended-type-checked"
in an ESLint configuration enables this rule.
This rule requires type information to run.
It is considered good practice to only throw
the Error
object itself or an object using the Error
object as base objects for user-defined exceptions.
The fundamental benefit of Error
objects is that they automatically keep track of where they were built and originated.
This rule restricts what can be thrown as an exception.
no-throw-literal
This rule was formerly known as no-throw-literal
.
The new name is a drop-in replacement with identical functionality.
Examples
This rule is aimed at maintaining consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an Error
object.
- ❌ Incorrect
- ✅ Correct
throw 'error';
throw 0;
throw undefined;
throw null;
const err = new Error();
throw 'an ' + err;
const err = new Error();
throw `${err}`;
const err = '';
throw err;
function getError() {
return '';
}
throw getError();
const foo = {
bar: '',
};
throw foo.bar;
Open in Playgroundthrow new Error();
throw new Error('error');
const e = new Error('error');
throw e;
try {
throw new Error('error');
} catch (e) {
throw e;
}
const err = new Error();
throw err;
function getError() {
return new Error();
}
throw getError();
const foo = {
bar: new Error(),
};
throw foo.bar;
class CustomError extends Error {
// ...
}
throw new CustomError();
Open in PlaygroundHow to Use
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"no-throw-literal": "off",
"@typescript-eslint/only-throw-error": "error"
}
};
Try this rule in the playground ↗
Options
See eslint/no-throw-literal
's options.
This rule adds the following options:
interface Options {
/**
* Whether to always allow throwing values typed as `any`.
*/
allowThrowingAny?: boolean;
/**
* Whether to always allow throwing values typed as `unknown`.
*/
allowThrowingUnknown?: boolean;
}
const defaultOptions: Options = {
allowThrowingAny: false,
allowThrowingUnknown: false,
};
When Not To Use It
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degredations after enabling type checked rules.