In this tutorial, we will see about the AggregateError in which we can combine the multiple errors into a single error instance.
AggregateError
The error is thrown when there is a possibility of multiple errors to be reported. AggregateError object takes multiple iterable Error
instances and wraps them in a single error.
Syntax
javascript
AggregateError(Array<Error>, "message");
How to throw an AggregateError
The way we throw the errors like Error
, TypeError
In a similar way we can throw this error.
javascript
throw new AggregateError([
new Error("Required field are missing"),
new TypeError("Typeof error for Status field"),
], "Common Error Message for your operation");
How to catch and show an Error
If the error type is of instanceof AggregateError
then it will contain the error message and an array of errors.
javascript
try {
throw new AggregateError([
new Error("Required field are missing"),
new TypeError("Typeof error for Status field"),
], "Common Error Message for your operation");
} catch(e) {
console.log(e instanceof AggregateError); //true
console.log(e.message)
//Common Error Message for your operation
console.log(e.name)
//AggregateError
console.log(e.errors);
// [Error: "Required field are missing", Error: "Typeof error for Status field"]
}
Usage / Use Cases
-
During
Promise.all
orPromise.any
all errors from all async operations will be caught with one error object. It can help you to provide detailed error messages. -
If you are a backend or API developer, you can collect all the validation errors or expectations in an array and report it once.
It makes easy by instantiating one object for each request and lets you collect many errors from ACLs, Authentication, Validation, etc. - Using this you do not have to stop the execution in the middle of the process and skip the other part by throwing an error object. All you can do is pass or collect an Error in an array object and finally deal with the errors if at all required.
Get More tutorials on JavaScript