0 day streak
javascript / expert
Snippet

Strategic Error Aggregation in Batch Processing

AggregateError provides a native way to wrap multiple errors into a single object. In complex Node.js microservices, this allows a batch operation to attempt all sub-tasks and report every failure at once, rather than stopping at the first error, which is crucial for data consistency and debugging distributed systems.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
async function processBatch(tasks) {
const results = await Promise.allSettled(tasks.map(t => t()));
const failures = results
.filter(r => r.status === 'rejected')
.map(r => r.reason);
if (failures.length > 0) {
throw new AggregateError(failures, 'Batch processing encountered errors');
}
}
try {
await processBatch(myTasks);
} catch (e) {
if (e instanceof AggregateError) {
for (const error of e.errors) console.error(error.message);
}
}
nodejs
Breakdown
1
throw new AggregateError(failures, '...');
Throws a single error containing an array of multiple underlying errors.
2
for (const error of e.errors)
Iterates through all individual errors captured in the aggregate.