Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Collect errors with AggregateError in JavaScript

36 Collecting failures into an AggregateError

fair

Upload four batches, two of which fail, and report every failure in one error instead of the first. Use allSettled to gather them and AggregateError to carry them, then check what it does and does not expose.

Stuck? Three hints, smallest first
  1. 1. allSettled never rejects, so you decide what a partial failure means.
  2. 2. new AggregateError(reasons, message) — the reasons come first, the summary second.
  3. 3. It copies whatever iterable you hand it into a plain array, and that array is not enumerable.

The answer

const uploads = () => [
  Promise.resolve('ikeja receipts'),
  Promise.reject(new Error('yaba: timed out')),
  Promise.resolve('lekki receipts'),
  Promise.reject(new Error('ajah: 500 from the API')),
];

async function allOrReport(tasks) {
  const settled = await Promise.allSettled(tasks);
  const failures = settled.filter((r) => r.status === 'rejected').map((r) => r.reason);
  if (failures.length) {
    throw new AggregateError(failures, `${failures.length} of ${settled.length} uploads failed`);
  }
  return settled.map((r) => r.value);
}

const agg = await allOrReport(uploads()).catch((err) => err);
const clean = await allOrReport([Promise.resolve('one'), Promise.resolve('two')]);
const fromSet = new AggregateError(new Set([new Error('a'), new Error('b')]), 'from any iterable');
const nested = new Error('nightly batch failed', { cause: agg });
const builtForYou = await Promise.any([
  Promise.reject(new Error('mirror 1 down')),
  Promise.reject(new Error('mirror 2 down')),
]).catch((err) => [err.name, err.errors.length, err.message.length > 0]);

console.log('summary  :', agg.message);
console.log('reasons  :', agg.errors.map((e) => e.message));
console.log('clean run:', clean);
console.log('serialise:', JSON.stringify(agg), Object.keys(agg));

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('an AggregateError carries every reason, in input order', agg.errors.map((e) => e.message), ['yaba: timed out', 'ajah: 500 from the API']);
test('with one message summarising them', agg.message, '2 of 4 uploads failed');
test('it is an Error, so an ordinary catch still holds it', [agg instanceof AggregateError, agg instanceof Error], [true, true]);
test('nothing is thrown when nothing failed', clean, ['one', 'two']);
test('any iterable of reasons is copied into a plain array', [Array.isArray(fromSet.errors), fromSet.errors.length], [true, 2]);
test('errors is non-enumerable too, so it does not serialise', [Object.keys(agg), JSON.stringify(agg)], [[], '{}']);
test('an aggregate nests inside a cause like any other error', nested.cause.errors.length, 2);
test('Promise.any builds one for you when every input fails', builtForYou, ['AggregateError', 2, true]);

This is the shape to reach for whenever failures are independent. Promise.all answers "did anything fail" and throws away the rest; allSettled plus AggregateError answers "what exactly failed", which is the only useful thing to put in a nightly job's alert. Two of four uploads failing is one incident with two lines, not one line and a shrug.

errors is in input order, not completion order, which is what makes it worth correlating with your input list — index 1 and index 3 of the batch, every time you run it. Note also that the summary message is yours to write. Promise.any's automatic one is engine-specific wording, which is why the assertion only checks that it is non-empty rather than what it says.

The serialisation line repeats exercise 35's lesson because it bites twice: errors follows the same non-enumerable rule as cause, so an aggregate posted to a log endpoint as JSON arrives as {} and you learn nothing. Flatten it yourself — { message, errors: agg.errors.map(toPlain) } — which is exactly the projection exercise 42 writes.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.