The JavaScript AggregateError object is used to reflect the overall error of many single errors. This can be used when multiple errors need to be represented in the form of a combined error, for example, it can be thrown by Promise.any() when all the promises passed to it are rejected.
Construction: The constructor AggregateError() is used to create a new object of AggregateError.
Instance Properties: This object has two properties:
- message: We use the AggregateError.prototype.message to display the message of error. The default error message shown is ” “.
- name: We use the AggregateError.prototype.name to display the name of error. The default error name shown is AggregateError.
Example 1: This example shows the catching of an AggregateError.
Javascript
<script> Promise.any([ Promise.reject( new Error( "There is any error occurred" ) ), ]). catch (n => { // Check if AggregateError console.log( n instanceof AggregateError ); // Print the message of the error console.log(n.message); // Print the name of the error console.log(n.name); // Print all the errors that this // error comprises console.log(n.errors); } );</script> |
Output:
true All promises were rejected AggregateError [Error: There is any error occurred]
Example 2: This example shows the creating of an AggregateError.
Javascript
<script> try { throw new AggregateError([ new Error( "This is Error 1" ), new Error( "This is Error 2" ), new Error( "This is Error 3" ), ], 'These are multiple errors' ); } catch (n) { // Check if AggregateError console.log( n instanceof AggregateError ); // Print the message of the error console.log(n.message); // Print the name of the error console.log(n.name); // Print all the errors that this // error comprises console.log(n.errors); } </script> |
Output:
true These are multiple errors AggregateError [Error: This is Error 1, Error: This is Error 2, Error: This is Error 3]