Sub topic 11
When Every Input Rejects: AggregateError
This chapter assumes you know how Promise.any picks the first fulfilled input, and that you are comfortable with try/catch around await. Here we look at the one case where Promise.any rejects: every input has rejected.
Why a Single Reason Is Not Enough
Promise.all and Promise.race reject with one reason, taken from one input. Promise.any cannot do that. It rejects only after all inputs have failed, so no single failure explains the outcome. Picking the first or last reason would hide the others.
To keep every reason, Promise.any rejects with an AggregateError. This is a built-in subclass of Error with an extra errors property, which is an array of every rejection reason.
The errors Array Follows Input Order
The reasons appear in the order of the inputs, not the order in which they rejected. This works the same way as result ordering in Promise.all.
const rejectAfter = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function main() {
try {
await Promise.any([
rejectAfter(200, 'primary down'), // rejects last
rejectAfter(50, 'mirror down'), // rejects first
rejectAfter(100, 'cache miss')
]);
} catch (err) {
console.log(err instanceof AggregateError); // true
console.log(err instanceof Error); // true
console.log(err.errors.map((e) => e.message));
// ['primary down', 'mirror down', 'cache miss']
}
}
main();Because the order is stable, you can match each reason to its source by index. This is handy when the inputs come from a list of URLs or server names.
Reading AggregateError in a catch Block
The message of an AggregateError from Promise.any is a generic string chosen by the engine, such as "All promises were rejected". It does not describe any particular failure. The useful information is in errors.
Code inside a catch block can also throw errors that have nothing to do with the combinator. Check the type before you read errors:
async function loadConfig(sources) {
try {
return await Promise.any(sources.map((load) => load()));
} catch (err) {
if (err instanceof AggregateError) {
const details = err.errors
.map((reason, i) => ` source ${i}: ${reason instanceof Error ? reason.message : String(reason)}`)
.join('\n');
throw new Error(`No config source succeeded:\n${details}`, { cause: err });
}
throw err;
}
}
loadConfig([
() => Promise.reject(new Error('file not found')),
() => Promise.reject('env var missing') // a non-Error reason
]).catch((err) => console.log(err.message));
// No config source succeeded:
// source 0: file not found
// source 1: env var missingTwo details matter here:
- A rejection reason can be any value, not only an
Error. Theinstanceof Errorcheck stops the code from reading.messageon a plain string. - Passing
{ cause: err }keeps the originalAggregateErrorattached, so logging tools can still show every reason.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Logging only `err.message` | You see a generic message and lose the real causes | Log or format `err.errors` |
| Assuming `errors[0]` failed first | You get the wrong idea about which failure came first | Treat indexes as input positions |
| Reading `err.errors` without a type check | `undefined` for errors that are not aggregates | Check `instanceof AggregateError` first |
You can also create one yourself with new AggregateError(errors, message) when your own code needs to report several failures at once:
const err = new AggregateError([new Error('x'), new Error('y')], 'Two checks failed');
console.log(err.message, err.errors.length); // Two checks failed 2Exercise
Promise.any receives three promises. Input 0 rejects with 'A' after 300 ms, input 1 rejects with 'B' after 100 ms, and input 2 rejects with 'C' after 200 ms. When does the returned promise reject, and what does err.errors contain?
Show answer
It rejects at about 300 ms, once the last input has rejected. err.errors is ['A', 'B', 'C'], which is input order, not the order in which the inputs rejected.
Exercise
Why should a catch block check err instanceof AggregateError before reading err.errors?
Show answer
The try block or the code around it can throw other kinds of errors, and those have no errors array. Without the check, err.errors is undefined and mapping over it throws a TypeError that hides the original error.