Index

no-throw-literal

不允许将字面作为异常抛出

通常认为好的做法是仅 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 对象的表达式。

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

规则详情

🌐 Rule Details

该规则旨在通过禁止抛出字面量和其他不可能是 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.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-throw-literal: "error"*/

throw "error";

throw 0;

throw undefined;

throw null;

const err = new Error();
throw "an " + err;
// err is recast to a string literal

const er2 = new Error();
throw `${err2}`

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint no-throw-literal: "error"*/

throw new Error();

throw new Error("error");

const e = new Error("error");
throw e;

try {
    throw new Error("error");
} catch (e) {
    throw e;
}

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

已知限制

🌐 Known Limitations

由于静态分析的限制,此规则无法保证你只会抛出 Error 对象。

🌐 Due to the limits of static analysis, this rule cannot guarantee that you will only throw Error objects.

这个规则的正确代码示例,但不会抛出 Error 对象:

🌐 Examples of correct code for this rule, but which do not throw an Error object:

在线运行
/*eslint no-throw-literal: "error"*/

const err = "error";
throw err;

function foo(bar) {
    console.log(bar);
}
throw foo("error");

throw new String("error");

const baz = {
    bar: "error"
};
throw baz.bar;

版本

此规则是在 ESLint v0.15.0 中引入。

资源