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.
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.
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);
}AggregateError two steps failed
[ 'Error: db down', 'TypeError: bad input' ]
AggregateError 2The 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.