AggregateError

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.

Đối tượng AggregateError đại diện cho một lỗi khi nhiều lỗi cần được gói trong một lỗi duy nhất. Nó được ném ra khi nhiều lỗi cần được báo cáo bởi một hoạt động, ví dụ như bởi Promise.any(), khi tất cả các promise truyền vào nó đều bị từ chối.

So với SuppressedError, AggregateError đại diện cho danh sách các lỗi không liên quan, trong khi SuppressedError đại diện cho một lỗi xảy ra trong quá trình xử lý một lỗi khác.

AggregateError là lớp con của Error.

Constructor

AggregateError()

Tạo đối tượng AggregateError mới.

Thuộc tính instance

Cũng kế thừa các thuộc tính instance từ lớp cha Error.

Các thuộc tính này được định nghĩa trên AggregateError.prototype và được chia sẻ bởi tất cả các instance AggregateError.

AggregateError.prototype.constructor

Hàm constructor đã tạo đối tượng instance. Đối với các instance AggregateError, giá trị khởi tạo là constructor AggregateError.

AggregateError.prototype.name

Đại diện cho tên của kiểu lỗi. Đối với AggregateError.prototype.name, giá trị khởi tạo là "AggregateError".

Các thuộc tính này là thuộc tính riêng của mỗi instance AggregateError.

errors

Một mảng đại diện cho các lỗi đã được tổng hợp.

Phương thức instance

Kế thừa các phương thức instance từ lớp cha Error.

Ví dụ

Bắt 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" ]
});

Tạo 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" ]
}

Đặc tả kỹ thuật

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

Tương thích trình duyệt

Xem thêm