Friday, January 10, 2025
Google search engine
HomeLanguagesJavascriptJavaScript AggregateError object

JavaScript AggregateError object

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]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments