Sub topic 12
Reporting Several Failures with AggregateError
Sometimes one operation fails for more than one reason at once. A batch of requests can have three failures, and a form can have four invalid fields. Throwing only the first error hides the others. AggregateError is a built-in error type (added in ES2021) that holds a list of errors in one object.
This chapter assumes you know Promise.allSettled, async/await, custom error classes that call super(message, options), and the cause option from earlier chapters.
What AggregateError Contains
AggregateError is a subclass of Error. Its constructor takes the list of errors first, then the message and the options:
const err = new AggregateError(
[new TypeError('Expected a string'), new RangeError('Age must be 0-150')],
'Two checks failed'
);
console.log(err.name); // 'AggregateError'
console.log(err.message); // 'Two checks failed'
console.log(err.errors.length); // 2
console.log(err.errors[0] instanceof TypeError); // true
console.log(err instanceof Error); // true
console.log(Object.keys(err)); // []
console.log(Object.getOwnPropertyDescriptor(err, 'errors').enumerable); // falseThe errors property works like message and cause. It is an own property, writable and configurable, and not enumerable. That is why Object.keys returns an empty array.
The constructor's argument order
The argument order catches people out. With a plain Error, the message comes first. With AggregateError, the errors come first:
| Constructor | First argument | Second argument | Third argument |
|---|---|---|---|
| `new Error(...)` | message | options (`{ cause }`) | none |
| `new AggregateError(...)` | iterable of errors | message | options (`{ cause }`) |
If you write new AggregateError('Something failed') by mistake, it does not throw. A string is iterable, so you get an aggregate whose errors holds one character per entry and whose message is empty. If you leave the first argument out, or pass something that is not iterable, the constructor throws a TypeError:
try {
new AggregateError();
} catch (e) {
console.log(e instanceof TypeError); // true
}
const oops = new AggregateError('Bad');
console.log(oops.errors); // [ 'B', 'a', 'd' ]
console.log(oops.message); // ''The errors array is a copy
The constructor reads the iterable into a new array. Changing your original collection later does not change the aggregate. Any iterable works, including a Set or a generator:
const list = [new Error('a')];
const agg = new AggregateError(list);
list.push(new Error('b'));
console.log(agg.errors.length); // 1
console.log(agg.errors === list); // false
console.log(agg.message); // '' (the default when no message is passed)
const fromSet = new AggregateError(new Set([new Error('x'), new Error('y')]), 'From a set');
console.log(fromSet.errors.length); // 2The entries can be any values, the same as anything you can throw or reject with. Code that reads errors should not assume every entry is an Error.
Collecting Failures from Concurrent Work
The most common use is a batch of promises where you want every failure, not only the first. Promise.all rejects as soon as one input rejects and drops the rest. Promise.allSettled waits for all of them, and you then build the aggregate yourself:
function fetchUser(id) {
return id % 2 === 0
? Promise.resolve({ id, name: `User ${id}` })
: Promise.reject(new Error(`User ${id} unavailable`));
}
async function fetchAllUsers(ids) {
const results = await Promise.allSettled(ids.map(fetchUser));
const failures = results
.filter((r) => r.status === 'rejected')
.map((r) => r.reason);
if (failures.length > 0) {
throw new AggregateError(failures, `${failures.length} of ${ids.length} requests failed`);
}
return results.map((r) => r.value);
}
fetchAllUsers([1, 2, 3, 4]).catch((err) => {
console.log(err.message); // '2 of 4 requests failed'
for (const e of err.errors) console.log(' -', e.message);
// - User 1 unavailable
// - User 3 unavailable
});Throwing here throws away the two users that loaded. Decide whether that is right for your case. If the caller can use partial results, return something like { users, failures } and don't throw. Throw an aggregate when partial success means the operation failed.
Promise.any creates one for you
Promise.any resolves with the first promise that fulfills. If every input rejects, it rejects with an AggregateError whose errors holds the rejection reasons in input order:
const fromMirror = (name, ok) =>
ok ? Promise.resolve(`data from ${name}`) : Promise.reject(new Error(`${name} is down`));
async function loadFromAnyMirror() {
try {
return await Promise.any([fromMirror('eu', false), fromMirror('us', false)]);
} catch (err) {
if (err instanceof AggregateError) {
console.log(err.errors.map((e) => e.message)); // [ 'eu is down', 'us is down' ]
}
throw err;
}
}
loadFromAnyMirror().catch(() => {});
Promise.any([]).catch((err) => {
console.log(err instanceof AggregateError, err.errors.length); // true 0
});The message comes from the engine (V8 uses 'All promises were rejected'), so don't match on it in code. An empty input array rejects at once with an empty errors list, which can surprise you when the list of mirrors comes from configuration.
Subclassing AggregateError
You can extend AggregateError the same way you extend Error. Pass all three arguments to super so errors and cause are both set up, then set name. Validation is a good fit, because users want to see every invalid field at once:
class FieldError extends Error {
constructor(field, message, options) {
super(message, options);
this.name = 'FieldError';
this.field = field;
}
}
class ValidationErrors extends AggregateError {
constructor(errors, message = 'Validation failed', options) {
super(errors, message, options);
this.name = 'ValidationErrors';
}
get fields() {
return this.errors.map((e) => e.field);
}
}
function validateSignup(input) {
const errors = [];
if (!input.email) errors.push(new FieldError('email', 'Email is required'));
if (!input.password || input.password.length < 8) {
errors.push(new FieldError('password', 'Password must be at least 8 characters'));
}
if (errors.length > 0) throw new ValidationErrors(errors);
return input;
}
try {
validateSignup({ email: '', password: 'abc' });
} catch (err) {
console.log(err instanceof ValidationErrors); // true
console.log(err instanceof AggregateError); // true
console.log(err.fields); // [ 'email', 'password' ]
}Catch blocks can now check for ValidationErrors specifically, and generic code that knows only about AggregateError still works with it.
errors Versus cause
Both properties attach other errors to the one you throw, but they mean different things:
| Property | Holds | Meaning |
|---|---|---|
| `cause` | One value | The lower-level failure that led to this error |
| `errors` | An array | Separate failures that together make up this error |
You can use both. For example, a ValidationErrors thrown while importing a file could carry the field errors in errors, while { cause } records the parse step that started the import. In practice, use cause when you wrap an error at a layer boundary, and use errors when there were several separate failures.
Handling Nested Aggregates
Aggregates can contain other aggregates. One example is a batch of jobs where each job ran Promise.any. A small generator flattens them into the individual failures. The seen set protects against cycles, which can only happen if someone pushes an aggregate into its own writable errors array:
function* leafErrors(err, seen = new Set()) {
if (seen.has(err)) return;
seen.add(err);
if (err instanceof AggregateError) {
for (const inner of err.errors) yield* leafErrors(inner, seen);
} else {
yield err;
}
}
const nested = new AggregateError(
[new Error('disk full'), new AggregateError([new Error('eu down'), new Error('us down')])],
'Backup failed'
);
console.log([...leafErrors(nested)].map((e) => e.message));
// [ 'disk full', 'eu down', 'us down' ]Common Mistakes
- Expecting the inner errors in the text output.
String(err)anderr.toString()give only'AggregateError: message'. Node'sconsole.logprints theerrorstoo, but most log formatters and error trackers do not. Write a message that states the count, and log the entries yourself. The serialization chapter covers this. - Expecting JSON to include them.
JSON.stringifyskipserrorsbecause it is not enumerable. - Wrapping a single failure. An aggregate holding one error forces every handler to unwrap it. Some teams throw the lone error directly when
failures.length === 1. Whatever you choose, use it everywhere, because callers then have to handle both shapes. - Running on old engines.
AggregateErrorneeds Node.js 15+ or a 2020-era browser. A polyfill is required for older targets.
Exercise
What do err.message and err.errors.length hold after const err = new AggregateError(['a', 'b'])? And what goes wrong with new AggregateError('Upload failed', [e1, e2])?
Show answer
err.message is an empty string and err.errors.length is 2. The entries are the strings 'a' and 'b', since any value is allowed. In the second call the arguments are swapped. The string 'Upload failed' is iterable, so errors becomes an array of its 13 characters, and the array [e1, e2] is converted to a string and used as the message. Write new AggregateError([e1, e2], 'Upload failed') instead.
Exercise
A catch block after await Promise.any(tasks) checks if (err instanceof TimeoutError) and never matches, even though every task timed out. Why, and how would you fix it?
Show answer
When every input rejects, Promise.any rejects with an AggregateError, not with any of the individual reasons. Check err instanceof AggregateError and then test err.errors.every((e) => e instanceof TimeoutError), or use a flattening helper such as leafErrors if the aggregates can be nested.
Exercise
Write a function settleOrThrow(promises, label) that resolves with an array of values when every promise fulfills, and otherwise throws an AggregateError with the message "<label>: N failed". Pass the first failure as cause so tools that follow only cause still find something.
Show answer
async function settleOrThrow(promises, label) { const results = await Promise.allSettled(promises); const failures = results.filter((r) => r.status === 'rejected').map((r) => r.reason); if (failures.length > 0) { throw new AggregateError(failures, ${label}: ${failures.length} failed, { cause: failures[0] }); } return results.map((r) => r.value); }