Sub topic 11
When Every Input Rejects: AggregateError
Promise.any waits for the first input that fulfills and ignores rejections along the way. Sometimes no input fulfills. Every mirror is down, every cache misses, or every fallback fails. In that case Promise.any has several rejection reasons and no single one is the correct answer. It rejects with an AggregateError, an error object that holds all of those reasons together.
This chapter assumes you know how Promise.any picks a winner (previous chapter), along with try/catch, async/await, and the Error class. Here you will learn what an AggregateError contains, which order its reasons come in, how to log it without losing information, and how to create one yourself.
How Promise.any Ends Up Rejecting
Promise.any keeps a list with one slot per input. When an input rejects, its reason goes into that input's slot. If any input fulfills, the list is thrown away and the combinator fulfills with that value. Once the last outstanding input has rejected and every slot is filled, Promise.any rejects with a new AggregateError whose errors property is that list.
Two consequences follow. First, an AggregateError from Promise.any always means every input rejected. It never reports a partial failure. Second, the rejection cannot arrive before the slowest input has settled. If one input hangs forever, Promise.any stays pending forever, even when all the other inputs failed long ago. Pair it with the timeout pattern from the Promise.race chapter when that matters.
Anatomy of an AggregateError
AggregateError is a subclass of Error, added in ES2021. It is available in Node.js 15+ and in all current browsers.
| Property | What it holds | Notes |
|---|---|---|
| `name` | `'AggregateError'` | Inherited from `AggregateError.prototype` |
| `message` | A generic text | Wording differs by engine; V8 uses "All promises were rejected" |
| `errors` | Array of rejection reasons | Ordered by input position, not by rejection time |
| `stack` | Stack trace | Points at the combinator's internals, not at the failures |
| `cause` | Optional underlying cause | Only set if you pass `{ cause }` when constructing one yourself |
The order of errors is the detail people most often get wrong. It follows input order, the same rule Promise.all uses for its results:
const rejectAfter = (ms, msg) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), ms));
async function main() {
try {
await Promise.any([
rejectAfter(300, 'slow A'),
rejectAfter(100, 'fast B'),
rejectAfter(200, 'mid C')
]);
} catch (err) {
console.log(err instanceof AggregateError); // true
console.log(err instanceof Error); // true
console.log(err.name); // 'AggregateError'
console.log(err.errors.map((e) => e.message));
// ['slow A', 'fast B', 'mid C'] (input order, even though B rejected first)
}
}
main();Because of this ordering, err.errors[i] always belongs to the input at index i. You can zip the reasons with your original list of sources to find out which source produced which failure.
Reasons Are Stored As-Is
Promise.any does not wrap or normalize the reasons. Whatever value an input rejected with goes into errors unchanged. If code rejects with a string, an object, or undefined, you get exactly that value back:
async function main() {
try {
await Promise.any([
Promise.reject(new Error('network down')),
Promise.reject('timeout'),
Promise.reject({ code: 503 }),
Promise.reject()
]);
} catch (err) {
for (const reason of err.errors) {
console.log(reason instanceof Error ? reason.message : reason);
}
// network down
// timeout
// { code: 503 }
// undefined
}
}
main();Code that runs err.errors.map((e) => e.message) breaks on these inputs: it prints undefined for some entries or throws on the undefined entry. When reasons come from code you don't control, normalize them before you use them.
Logging Without Losing the Details
An AggregateError can look nearly empty, depending on how you print it:
const err = new AggregateError([new Error('A'), new Error('B')], 'All failed');
console.log(String(err)); // 'AggregateError: All failed'
console.log(JSON.stringify(err)); // '{}'
console.log(Object.keys(err)); // []The errors property is non-enumerable, just like message and stack. So JSON.stringify, object spread, and many structured loggers skip it. Recent Node.js versions show [errors]: [...] when you pass the error object straight to console.log. Browser consoles let you expand it. Log shippers and String(err) drop it.
To keep the reasons, serialize them explicitly:
function describeReason(reason) {
if (reason instanceof Error) return `${reason.name}: ${reason.message}`;
try {
return JSON.stringify(reason) ?? String(reason);
} catch {
return String(reason);
}
}
function serializeAggregate(err) {
return {
name: err.name,
message: err.message,
errors: err.errors.map(describeReason)
};
}
const err = new AggregateError([new Error('A'), 'B'], 'All failed');
console.log(JSON.stringify(serializeAggregate(err)));
// {"name":"AggregateError","message":"All failed","errors":["Error: A","\"B\""]}Turning AggregateError into a Useful Error
In practice you usually catch the AggregateError near the Promise.any call and throw an error that names the failed sources. Pass the original as cause, so nothing is lost for debugging:
async function firstAvailable(sources) {
try {
return await Promise.any(sources.map((source) => source.load()));
} catch (err) {
if (!(err instanceof AggregateError)) throw err;
const details = err.errors.map((reason, i) => {
const text = reason instanceof Error ? reason.message : String(reason);
return ` ${sources[i].name}: ${text}`;
});
throw new Error(
`All ${sources.length} sources failed:\n${details.join('\n')}`,
{ cause: err }
);
}
}
const sources = [
{ name: 'primary', load: () => Promise.reject(new Error('HTTP 500')) },
{ name: 'replica', load: () => Promise.reject(new Error('ECONNREFUSED')) },
{ name: 'cache', load: () => Promise.reject(new Error('miss')) }
];
firstAvailable(sources).catch((err) => {
console.log(err.message);
// All 3 sources failed:
// primary: HTTP 500
// replica: ECONNREFUSED
// cache: miss
console.log(err.cause instanceof AggregateError); // true
});The instanceof AggregateError guard matters because other errors can reach the same catch block. If a load() function throws synchronously, the exception leaves sources.map before Promise.any ever runs, and it arrives as a plain error. Passing something that isn't iterable to Promise.any produces a TypeError rejection. Rethrowing anything that is not an AggregateError keeps those bugs visible. Without the guard, they would be relabeled as "all sources failed".
The Empty-Input Case
Promise.any([]) rejects right away with an AggregateError whose errors array is empty. Since the list has no inputs, no input can fulfill. The edge-cases chapter covers this in more detail. Here, note that "all sources failed" with zero sources usually points to a configuration bug, not an outage. Check for it separately:
async function main() {
try {
await Promise.any([]);
} catch (err) {
if (err instanceof AggregateError && err.errors.length === 0) {
console.log('No sources were configured');
}
}
}
main();Creating AggregateError Yourself
The constructor is public, so you can use AggregateError anywhere you need to report several failures at once. Its signature is new AggregateError(errors, message, options). Here, errors is any iterable and gets copied into a new array, and options may contain cause.
A common use is turning Promise.allSettled results into a single error when you need every task to run but still want to fail if any of them failed:
async function runAll(tasks) {
const outcomes = await Promise.allSettled(tasks.map((task) => task()));
const failures = outcomes
.filter((outcome) => outcome.status === 'rejected')
.map((outcome) => outcome.reason);
if (failures.length > 0) {
throw new AggregateError(
failures,
`${failures.length} of ${outcomes.length} tasks failed`
);
}
return outcomes.map((outcome) => outcome.value);
}
runAll([
() => Promise.resolve(1),
() => Promise.reject(new Error('disk full')),
() => Promise.reject(new Error('quota exceeded'))
]).catch((err) => {
console.log(err.message); // '2 of 3 tasks failed'
console.log(err.errors.map((e) => e.message)); // ['disk full', 'quota exceeded']
});The behavior differs from the Promise.any version in two ways. Your message can say something specific. The errors array now holds only the failures, so its indexes no longer line up with the inputs. If callers need to know which task failed, attach the index or a label to each reason before you build the error.
Common Mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Reading only `err.message` | Logs say "All promises were rejected" with no detail | Iterate `err.errors` |
| Assuming `errors` is in rejection order | Wrong source blamed for a failure | Index by input position |
| Calling `.message` on every reason | `undefined` or a `TypeError` for non-Error reasons | Normalize with an `instanceof Error` check |
| `JSON.stringify(err)` | Produces `{}` | Serialize `errors` explicitly |
| Catching every error as "all failed" | Programming bugs get hidden | Guard with `instanceof AggregateError` |
| Expecting a quick failure | Hangs if one input never settles | Add a timeout with `Promise.race` |
Exercise
Three promises are passed to Promise.any in this order: p0 rejects with new Error('x') after 50 ms, p1 rejects with the string 'y' after 10 ms, and p2 rejects with new Error('z') after 30 ms. What is err.errors, and when does the AggregateError arrive?
Show answer
err.errors is [Error('x'), 'y', Error('z')], which is input order, with the string 'y' stored unchanged rather than wrapped in an Error. The rejection arrives after about 50 ms, once the last input (p0) has rejected.
Exercise
A handler does catch (err) { logger.error(JSON.stringify(err)); } around Promise.any, and the logs show only {}. Why, and what should it log instead?
Show answer
AggregateError's errors, message, and stack properties are non-enumerable, so JSON.stringify skips them. Log an explicit object instead, such as { name: err.name, message: err.message, errors: err.errors.map(r => r instanceof Error ? r.message : String(r)) }.
Exercise
Why should a catch block around Promise.any check err instanceof AggregateError before reporting "all sources failed"?
Show answer
Other errors can reach the same catch block. Examples are a synchronous throw while building the promise array, or a TypeError when the argument isn't iterable. These are bugs, not source failures, so they should be rethrown unchanged instead of being reported as an outage.