Skip to main content

only-throw-error

禁止抛出非 Error 值作为异常.

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

🧱

This is an "extension" rule that replaces a core ESLint rule to work with TypeScript. See Rules > Extension Rules.

This rule extends the base no-throw-literal rule from ESLint core. 它使用类型信息来确定哪些值是 Error

¥It uses type information to determine which values are Errors.

Error 对象本身或使用 Error 对象作为用户定义异常的基础对象的对象被认为是一种良好做法。Error 对象的基本好处是它们会自动跟踪它们的构建和起源位置。

¥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.

:::infono-throw-literal][从以下对象迁移

此扩展规则以前称为 @typescript-eslint/no-throw-literal。新名称是具有相同功能的替代品。

¥This extension rule was formerly known as @typescript-eslint/no-throw-literal. The new name is a drop-in replacement with identical functionality.

:::

示例

¥Examples

此规则旨在通过禁止抛出字面量和其他不可能是 Error 对象的表达式来在抛出异常时保持一致性。

¥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

如何使用

eslint.config.mjs
export default tseslint.config({
rules: {
// Note: you must disable the base rule as it can report incorrect errors
"no-throw-literal": "off",
"@typescript-eslint/only-throw-error": "error"
}
});

在线运行试试这个规则 ↗

选项

See eslint/no-throw-literal's options.

¥Options

该规则添加了以下选项:

¥This rule adds the following options:

interface Options {
/**

* Type specifiers that can be thrown.
*/
allow?: (
| {
from: 'file';
name: [string, ...string[]] | string;
path?: string;
}
| {
from: 'lib';
name: [string, ...string[]] | string;
}
| {
from: 'package';
name: [string, ...string[]] | string;
package: string;
}
| string
)[];

/**

* 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 = {
allow: [],
allowThrowingAny: true,
allowThrowingUnknown: true,
};

何时不使用它

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 degradations after enabling type checked rules.

资源

Taken with ❤️ from ESLint core.