AggregateError

Baseline 廣泛可用 *

此功能已成熟,並可在許多裝置和瀏覽器版本上使用。自 2020 年 9 月起,所有瀏覽器均已提供此功能。

* 此特性的某些部分可能存在不同級別的支援。

AggregateError 物件表示當需要將多個錯誤封裝到單個錯誤中時產生的錯誤。當某個操作需要報告多個錯誤時,例如 Promise.any() 在其傳入的所有 Promise 都被拒絕時,就會丟擲它。

AggregateErrorError 的一個子類。

建構函式

AggregateError()

建立一個新的 AggregateError 物件。

例項屬性

還繼承了其父級 Error 的例項屬性。.

這些屬性定義在 AggregateError.prototype 上,並被所有 AggregateError 例項共享。

AggregateError.prototype.constructor

建立了例項物件的建構函式。對於 AggregateError 例項,初始值為 AggregateError 建構函式。

AggregateError.prototype.name

表示錯誤型別的名稱。對於 AggregateError.prototype.name,初始值為 "AggregateError"

這些屬性是每個 AggregateError 例項的自有屬性。

errors

一個數組,表示被聚合的錯誤。

例項方法

繼承了其父級 Error 的例項方法。.

示例

捕獲 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" ]
});

建立 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" ]
}

規範

規範
ECMAScript® 2026 語言規範
# sec-aggregate-error-objects

瀏覽器相容性

另見