Sub topic 12
Reporting Several Failures with AggregateError
This chapter assumes you know Promise.allSettled, async/await, and the cause option from earlier chapters. Sometimes one operation fails for several independent reasons at once. Examples include a batch of requests or a form with many invalid fields. Throwing only the first error hides the others. AggregateError is a built-in subclass of Error that carries a list of errors in one throwable object.
The Constructor and Its Properties
The signature is new AggregateError(errors, message, options):
errorsis any iterable, such as an array or a Set. It is copied into a new array on theerrorsproperty.messageis the usual human-readable summary.optionsacceptscause, just likeError.
const err = new AggregateError(
[new TypeError('bad id'), new RangeError('limit too high')],
'Invalid query',
{ cause: 'user input' }
);
console.log(err instanceof AggregateError); // true
console.log(err instanceof Error); // true
console.log(err.name); // 'AggregateError'
console.log(err.errors.length); // 2
console.log(err.errors[1].message); // 'limit too high'
console.log(err.cause); // 'user input'
console.log(Object.keys(err)); // []Like message and cause, the errors property is an own property that is not enumerable. As a result, JSON.stringify and Object.keys skip it, which matters when you log it later.
Collecting Failures from a Batch
Promise.all rejects on the first failure and drops the rest. Promise.allSettled waits for every promise, so you can collect all the rejection reasons and throw them together. Save this file as batch.mjs so that top-level await works, then run it with node batch.mjs.
const fetchA = async () => 'A ok';
const fetchB = async () => { throw new Error('B timed out'); };
const fetchC = async () => { throw new Error('C returned 500'); };
async function loadAll() {
const results = await Promise.allSettled([fetchA(), fetchB(), fetchC()]);
const failures = results
.filter((r) => r.status === 'rejected')
.map((r) => r.reason);
if (failures.length > 0) {
throw new AggregateError(failures, `${failures.length} requests failed`);
}
return results.map((r) => r.value);
}
try {
await loadAll();
} catch (err) {
if (err instanceof AggregateError) {
console.error(err.message); // '2 requests failed'
for (const e of err.errors) console.error(' -', e.message);
} else {
throw err;
}
}Promise.any Throws It for You
Promise.any resolves with the first promise that fulfills. If every input promise rejects, it rejects with an AggregateError. Its errors array holds the reasons in input order, not in the order they happened.
try {
await Promise.any([
Promise.reject(new Error('mirror 1 down')),
Promise.reject(new Error('mirror 2 down')),
]);
} catch (err) {
console.log(err instanceof AggregateError); // true
console.log(err.errors.map((e) => e.message)); // ['mirror 1 down', 'mirror 2 down']
}errors Versus cause
| Property | Holds | Meaning |
|---|---|---|
| `cause` | One value | The failure that led to this error |
| `errors` | An array | Sibling failures reported together |
You can use both. An AggregateError can have a cause, and each item in errors can have its own cause chain.
Common Mistakes
- Passing a single error instead of an iterable, as in
new AggregateError(err). This throws aTypeErrorbecause an Error object is not iterable. - Throwing an
AggregateErrorthat holds one item. Throw that error directly instead. - Logging with
JSON.stringify(err). The output is{}.
Exercise
You call Promise.any([p1, p2, p3]) and all three reject. What does the catch block receive, and how do you get the reason p2 rejected with?
Show answer
It receives an AggregateError. Its errors array lists the rejection reasons in input order, so p2's reason is err.errors[1].
Exercise
Why does console.log(Object.keys(new AggregateError([new Error('x')], 'm'))) print an empty array?
Show answer
The errors and message properties are own properties that are not enumerable, and name is inherited from the prototype, so Object.keys returns none of them.