Skip to main content

no-throw-literal

Disallow throwing literals 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.

warning

This rule is being renamed to only-throw-error. When it was first created, it only prevented literals from being thrown (hence the name), but it has now been expanded to only allow expressions which have a possibility of being an Error object. With the allowThrowingAny and allowThrowingUnknown options, it can be configured to only allow throwing values which are guaranteed to be an instance of Error.

The current name no-throw-literal will be removed in a future major version of typescript-eslint.

Options

See eslint/no-throw-literal options.

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/no-throw-literal": "error"
}
};

Try this rule in the playground ↗

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.