AggregateError

当需要将多个错误封装在一个错误中时,AggregateError 对象表示一个错误。当一个操作需要报告多个错误时(例如 Promise.any()),当传递给它的所有承诺都拒绝时,会抛出该错误。

¥The AggregateError object represents an error when several errors need to be wrapped in a single error. It is thrown when multiple errors need to be reported by an operation, for example by Promise.any(), when all promises passed to it reject.

AggregateErrorError 的子类。

¥AggregateError is a subclass of Error.

构造函数

¥Constructor

AggregateError()

创建一个新的 AggregateError 对象。

实例属性

¥Instance properties

还从其父级 Error 继承实例属性。

¥Also inherits instance properties from its parent Error.

这些属性在 AggregateError.prototype 上定义并由所有 AggregateError 实例共享。

¥These properties are defined on AggregateError.prototype and shared by all AggregateError instances.

AggregateError.prototype.constructor

创建实例对象的构造函数。对于 AggregateError 实例,初始值为 AggregateError 构造函数。

AggregateError.prototype.name

表示错误类型的名称。对于 AggregateError.prototype.name,初始值为 "AggregateError"

这些属性是每个 AggregateError 实例自己的属性。

¥These properties are own properties of each AggregateError instance.

errors

表示聚合的错误的数组。

实例方法

¥Instance methods

从其父级 Error 继承实例方法。

¥Inherits instance methods from its parent Error.

示例

¥Examples

捕获聚合错误

¥Catching an AggregateError

js
Promise.any([Promise.reject(new Error("some error"))]).catch((e) => {
  console.log(e instanceof AggregateError); // true
  console.log(e.message); // "All Promises rejected"
  console.log(e.name); // "AggregateError"
  console.log(e.errors); // [ Error: "some error" ]
});

创建聚合错误

¥Creating an AggregateError

js
try {
  throw new AggregateError([new Error("some error")], "Hello");
} catch (e) {
  console.log(e instanceof AggregateError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "AggregateError"
  console.log(e.errors); // [ Error: "some error" ]
}

规范

Specification
ECMAScript Language Specification
# sec-aggregate-error-objects

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看