Index

prefer-promise-reject-errors

需要使用 Error 对象作为 Promise 拒绝的原因

通常认为,将内置的 Error 对象实例传递给 reject() 函数用于 Promise 中的用户自定义错误是良好的做法。Error 对象会自动存储堆栈跟踪,可以通过确定错误来源来调试错误。如果一个 Promise 被非 Error 值拒绝,可能很难确定拒绝发生的位置。

🌐 It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises. Error objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non-Error value, it can be difficult to determine where the rejection occurred.

规则详情

🌐 Rule Details

此规则旨在确保 Promise 仅以 Error 对象被拒绝。

🌐 This rule aims to ensure that Promises are only rejected with Error objects.

选项

🌐 Options

此规则采用一个可选对象参数:

🌐 This rule takes one optional object argument:

  • allowEmptyReject: true(默认情况下为 false)允许调用无参数的 Promise.reject()

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint prefer-promise-reject-errors: "error"*/

Promise.reject("something bad happened");

Promise.reject(5);

Promise.reject();

new Promise(function(resolve, reject) {
  reject("something bad happened");
});

new Promise(function(resolve, reject) {
  reject();
});

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

🌐 Examples of correct code for this rule:

在线运行
/*eslint prefer-promise-reject-errors: "error"*/

Promise.reject(new Error("something bad happened"));

Promise.reject(new TypeError("something bad happened"));

new Promise(function(resolve, reject) {
  reject(new Error("something bad happened"));
});

const foo = getUnknownValue();
Promise.reject(foo);

使用 allowEmptyReject: true 选项时,此规则的正确代码示例:

🌐 Examples of correct code for this rule with the allowEmptyReject: true option:

在线运行
/*eslint prefer-promise-reject-errors: ["error", {"allowEmptyReject": true}]*/

Promise.reject();

new Promise(function(resolve, reject) {
  reject();
});

已知限制

🌐 Known Limitations

由于静态分析的限制,此规则无法保证你只会拒绝包含 Error 对象的 Promise。虽然该规则会报告可以明确保证拒绝原因绝对不是 Error 的情况,但在无法确定某个给定原因是否为 Error 的情况下,它不会报告这些情况。有关此警告的更多信息,请参见 no-throw-literal 规则中的 类似限制

🌐 Due to the limits of static analysis, this rule cannot guarantee that you will only reject Promises with Error objects. While the rule will report cases where it can guarantee that the rejection reason is clearly not an Error, it will not report cases where there is uncertainty about whether a given reason is an Error. For more information on this caveat, see the similar limitations in the no-throw-literal rule.

为了避免规则之间的冲突,此规则不会报告在异步函数中的 throw 语句使用的非错误值,即使这些会导致 Promise 拒绝。要对这些情况进行 lint,请使用 no-throw-literal 规则。

🌐 To avoid conflicts between rules, this rule does not report non-error values used in throw statements in async functions, even though these lead to Promise rejections. To lint for these cases, use the no-throw-literal rule.

何时不使用

🌐 When Not To Use It

如果你使用自定义非错误值作为 Promise 拒绝原因,你可以关闭此规则。

🌐 If you’re using custom non-error values as Promise rejection reasons, you can turn off this rule.

版本

此规则是在 ESLint v3.14.0 中引入。

进阶读物

资源