no-throw-literal

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

仅将 Error 对象本身或使用 Error 对象的对象作为用户定义异常的基础对象进行 throw 被认为是一种很好的做法。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;

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

var err = new Error();
throw `${err}`

此规则的正确代码示例:

¥Examples of correct code for this rule:

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

throw new Error();

throw new Error("error");

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

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

已知限制

¥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"*/

var err = "error";
throw err;

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

throw new String("error");

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

版本

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

资源

ESLint 中文网
粤ICP备13048890号