Course contentsShow
← JavaScript
Lesson 1147 of 2,72326. Error HandlingFree lesson

AggregateError for Multiple Failures

Learn how AggregateError bundles multiple errors together, useful for Promise.any rejections.

AggregateError for Multiple Failures

You'll learn how to bundle multiple errors into one convenient package using JavaScript's AggregateError.


What Problem Does AggregateError Solve?

Sometimes operations fail in multiple ways at once. Imagine trying several different servers simultaneously—some might time out, others might return bad data, and a few might refuse the connection entirely. Each failure is a separate error, but you need to report them all together.

AggregateError is a special error type that wraps an array of errors into a single error object. Think of it like a shipping box that contains multiple damaged items—you want to know about all the problems, not just the first one.

Basic Syntax

const errors = [
  new Error('Server 1 timeout'),
  new TypeError('Invalid response from Server 2'),
  new Error('Server 3 connection refused')
];

const aggregateError = new AggregateError(errors, 'Multiple servers failed');

The first argument is an array (or iterable) of errors. The second is an optional message describing the overall failure.

Accessing Individual Errors

The wrapped errors are available via the errors property:

try {
  throw new AggregateError(
    [new Error('First problem'), new Error('Second problem')],
    'Operation failed'
  );
} catch (err) {
  console.log(err.message); // "Operation failed"
  console.log(err.errors.length); // 2
  err.errors.forEach(e => console.log(e.message));
  // "First problem"
  // "Second problem"
}

Real-World Use: Promise.any

Promise.any uses AggregateError when all promises reject—it bundles every rejection reason together so you can inspect what went wrong with each attempt.

Key Takeaway: AggregateError packages multiple errors into one, preserving all failure details when operations fail in multiple ways simultaneously.