Skip to content
jshacks.dev
Fundamentals

Combine errors with AggregateError

Bundle several failures into one error with AggregateError, and see which APIs throw it, such as Promise.any and a filtered allSettled. Node.js 15.

2 min read
Summarize in AI

Promise.all rejects with the first failure and hides the rest. When every failure matters, AggregateError wraps them in one error with an errors array, and it has been in Node.js since version 15.

JavaScript
const results = await Promise.allSettled([
  Promise.reject(new Error('db down')),
  Promise.resolve('ok'),
  Promise.reject(new TypeError('bad input')),
]);

const failures = results.filter((r) => r.status === 'rejected').map((r) => r.reason);
const combined = new AggregateError(failures, 'two steps failed');

console.log(combined.name, combined.message);
console.log(combined.errors.map((e) => `${e.name}: ${e.message}`));

try {
  await Promise.any([Promise.reject(new Error('a')), Promise.reject(new Error('b'))]);
} catch (error) {
  console.log(error.constructor.name, error.errors.length);
}
Text
AggregateError two steps failed
[ 'Error: db down', 'TypeError: bad input' ]
AggregateError 2

The constructor takes an array of errors and an optional message. The example runs three tasks with Promise.allSettled, pulls the rejected reasons out, and builds one error with both failures, Error: db down and TypeError: bad input, in combined.errors. The built-in user is Promise.any: when every promise rejects, it rejects with an AggregateError, and the last line shows that errors.length is 2. The class is described in the specification for AggregateError.

The message is yours to write, because the built-in Promise.any error says only All promises were rejected. The errors array keeps the order of the input. A plain catch that logs error.message prints only the summary, so loop over errors when you report.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.