javascript / intermediate
Snippet
Handling Multiple Errors with AggregateError
AggregateError represents a single error that wraps multiple individual errors. This is particularly useful in Node.js when multiple parallel operations (like Promise.any) fail simultaneously.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
try {throw new AggregateError([new Error('Database connection failed'),new Error('API key expired')], 'System check failed');} catch (error) {if (error instanceof AggregateError) {console.log(error.message);error.errors.forEach(err => console.error(err.message));}}
nodejs
Breakdown
1
new AggregateError([...], 'message')
Creates a combined error object containing an array of specific errors.
2
error instanceof AggregateError
Checks if the caught error is a collection of multiple errors.
3
error.errors.forEach(...)
Iterates through the individual error objects stored inside the aggregate.