Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท JSON, Errors and Reflection

The AggregateError object

Reference for AggregateError: wrap several errors in one, read the errors array, and see how Promise.any() uses it when every promise rejects.

AggregateError is an error that carries a list of other errors. It exists for operations where many things can fail at once and you want to report all the failures together instead of just the first. The best-known user is Promise.any(): when every promise rejects, it rejects with an AggregateError whose errors array holds each reason.

You can also create one yourself, for example to collect validation problems or the failures of several parallel tasks and throw them as a single error.

JavaScript
const combined = new AggregateError([new Error("a"), new TypeError("b")], "Two things failed");
console.log(combined.errors.length); // 2

Try it

JS Creating and inspecting an AggregateError

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Promise.any() rejecting with all reasons

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
new AggregateError(errors)
new AggregateError(errors, message)
new AggregateError(errors, message, options)
Name Description
errors An iterable of values, usually errors. It is copied into an array stored as the errors property.
message Optional description.
options Optional object whose cause becomes error.cause.

Properties: errors (an array), plus the usual name ("AggregateError"), message and stack.

Exceptions: a TypeError if errors is not iterable. AggregateError can also be called without new.

Usage notes

  • errors is a copy. The constructor reads the iterable into a new array, so later changes to the original list do not show up, and combined.errors === problems is false.
  • Values need not be errors. Promise.any() stores whatever each promise rejected with, including strings, so check the type before reading .message.
  • Throwing it is your choice. Use it when several independent failures should be reported together; for a single failure throw a normal error with a cause.
  • Order follows input order, not the order in which the promises rejected, for Promise.any().
  • Compare with Promise.allSettled(), which never rejects and reports every outcome as data. Choose AggregateError when the combined failure should stop the flow.
  • Not enumerable. errors is an own, non-enumerable property, so JSON.stringify() does not include it. Map the errors to plain objects if you need to log them.
  • Message is empty by default when you construct one yourself; Promise.any() supplies its own text, which varies by engine.

Browser support

AggregateError and Promise.any() arrived together and are supported in current browsers and Node.js. Older environments may lack them, so check a compatibility table.