What is aggregate-error?
The aggregate-error package is used to create an Error instance that aggregates multiple errors into a single error object. This can be useful when you have several operations that may each throw errors, and you want to collect all of those errors into a single error object that can be thrown, returned, or logged.
What are aggregate-error's main functionalities?
Aggregating multiple errors
This feature allows you to collect multiple errors into a single error object. The code sample demonstrates how to create an instance of AggregateError with an array of Error objects and then throw it.
const AggregateError = require('aggregate-error');
const errors = [
new Error('First error'),
new Error('Second error')
];
const aggregatedError = new AggregateError(errors);
throw aggregatedError;
Iterating over aggregated errors
This feature allows you to iterate over the individual errors within an AggregateError instance. The code sample shows how to loop through each error using a for...of loop and log them to the console.
const AggregateError = require('aggregate-error');
const errors = [
new Error('First error'),
new Error('Second error')
];
const aggregatedError = new AggregateError(errors);
for (const error of aggregatedError) {
console.error(error);
}
Other packages similar to aggregate-error
verror
The verror package provides a way to create rich JavaScript errors. It allows you to chain errors, add context to them, and format multi-line error messages. It is similar to aggregate-error in that it helps manage multiple error objects, but it focuses more on providing additional context and information about single errors rather than aggregating multiple errors.
multi-error
Multi-error is another package that allows you to combine multiple errors into a single error object. It is similar to aggregate-error, but it has a different API and additional features such as filtering and mapping over the contained errors.
aggregate-error
Create an error from multiple errors
Install
$ npm install aggregate-error
Usage
const AggregateError = require('aggregate-error');
const error = new AggregateError([new Error('foo'), 'bar', {message: 'baz'}]);
throw error;
for (const individualError of error) {
console.log(individualError);
}
API
AggregateError(errors)
Returns an Error
that is also an Iterable
for the individual errors.
errors
Type: Array<Error|Object|string>
If a string, a new Error
is created with the string as the error message.
If a non-Error object, a new Error
is created with all properties from the object copied over.
License
MIT © Sindre Sorhus