Skip to main content

only-throw-error

Disallow throwing non-Error values as exceptions.

💭

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.

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.

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 Playground

How to Use

.eslintrc.cjs
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 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 Performance Troubleshooting if you experience performance degredations after enabling type checked rules.

Resources

Taken with ❤️ from ESLint core.