Skip to main content

no-throw-literal

Disallow throwing literals as exceptions.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict-type-checked" 可启用此规则。

💭

该规则需要 类型信息 才能运行。


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

该规则限制了可以作为异常抛出的内容。 当它第一次创建时,它仅阻止抛出字面量(因此得名),但现在它已扩展为仅允许有可能是 Error 对象的表达式。 对于 allowThrowingAnyallowThrowingUnknown,可以将其配置为仅允许抛出保证是 Error 实例的值。

英:This rule restricts what can be thrown as an exception. 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, it can be configured to only allow throwing values which are guaranteed to be an instance of Error.

示例

该规则旨在通过禁止抛出不可能是 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 err() {
return '';
}
throw err();

const foo = {
bar: '',
};
throw foo.bar;
Open in Playground

选项

该规则添加了以下选项:

英: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,
};

如何使用

.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"
}
};
在线运行试试这个规则 ↗

选项

参见 eslint/no-throw-literal 选项

资源

摘自 ❤️ ESLint 内核