错误:cause

Error 实例的 cause 数据属性指示错误的具体原始原因。

¥The cause data property of an Error instance indicates the specific original cause of the error.

当捕获错误并使用更具体或有用的错误消息重新抛出错误时,可以使用它,以便仍然可以访问原始错误。

¥It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error.

¥Value

options.cause 参数中传递给 Error() 构造函数的值。它可能不存在。

¥The value that was passed to the Error() constructor in the options.cause argument. It may not be present.

Property attributes of 错误:cause
Writable yes
Enumerable no
Configurable yes

描述

¥Description

cause 的值可以是任何类型。你不应该假设你捕获的错误的 causeError,就像你无法确定 catch 语句中绑定的变量是 Error 一样。下面的 "提供结构化数据作为错误原因" 示例显示了故意提供非错误作为原因的情况。

¥The value of cause can be of any type. You should not make assumptions that the error you caught has an Error as its cause, in the same way that you cannot be sure the variable bound in the catch statement is an Error either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause.

示例

¥Examples

重新抛出错误并给出原因

¥Rethrowing an error with a cause

有时捕获错误并用新消息重新抛出它是有用的。在这种情况下,你应该将原始错误传递到新 Error 的构造函数中,如图所示。

¥It is sometimes useful to catch an error and re-throw it with a new message. In this case you should pass the original error into the constructor for the new Error, as shown.

js
try {
  connectToDatabase();
} catch (err) {
  throw new Error("Connecting to database failed.", { cause: err });
}

有关更详细的示例,请参阅 错误 > 区分类似错误

¥For a more detailed example see Error > Differentiate between similar errors.

提供结构化数据作为错误原因

¥Providing structured data as the error cause

为人类使用而编写的错误消息可能不适合机器解析 - 因为它们会受到改写或标点符号更改的影响,这可能会破坏为使用它们而编写的任何现有解析。因此,当从函数抛出错误时,作为人类可读错误消息的替代方案,你可以将原因作为结构化数据提供,以供机器解析。

¥Error messages written for human consumption may be inappropriate for machine parsing — since they're subject to rewording or punctuation changes that may break any existing parsing written to consume them. So when throwing an error from a function, as an alternative to a human-readable error message, you can instead provide the cause as structured data, for machine parsing.

js
function makeRSA(p, q) {
  if (!Number.isInteger(p) || !Number.isInteger(q)) {
    throw new Error("RSA key generation requires integer inputs.", {
      cause: { code: "NonInteger", values: [p, q] },
    });
  }
  if (!areCoprime(p, q)) {
    throw new Error("RSA key generation requires two co-prime integers.", {
      cause: { code: "NonCoprime", values: [p, q] },
    });
  }
  // rsa algorithm…
}

规范

Specification
ECMAScript Language Specification
# sec-installerrorcause

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看