Up to date
Published
Updated on
6 min read

Trevor I. Lasn

Staff Software Engineer, Engineering Manager

AggregateError in JavaScript

Handle multiple errors at once

A few days ago, I was reviewing all the error types in JavaScript and came across something relatively new: AggregateError

AggregateError was added in ECMAScript 2021 (ES12). It’s designed to help when you need to deal with multiple errors at once. This is handy in scenarios like working with promises, where you might want to handle all errors together instead of one by one.

Here’s a quick overview of the built-in error types in JavaScript:

Error TypeDescription
ErrorBase error object for generic errors.
SyntaxErrorThrown when there is a syntax mistake in the code.
ReferenceErrorThrown when referencing a variable that doesn’t exist.
TypeErrorThrown when a value is not of the expected type.
RangeErrorThrown when a number is outside an allowable range.
URIErrorThrown when there is an issue with encoding/decoding URI components.
EvalErrorHistorical, used for improper eval() usage (mostly obsolete).
AggregateErrorThrown when multiple errors need to be handled together. (added in ECMAScript 2021)

If you use Promise.any() to find the first successful promise, but they all fail, JavaScript will throw an AggregateError. This error lists all the reasons why the promises failed.

  • Promise.any() to try fetching data from multiple APIs, resolving with the first successful result. If all promises fail, it throws an AggregateError.

  • Handle the potential errors with a try/catch block, where the try block deals with successful data fetching, and the catch block catches the AggregateError if all promises are rejected.

  • If an AggregateError occurs, I log the error details and then attempt to retry the operation up to a specified number of times, with a delay between each retry.

  • Implement the retry logic by recursively calling the function, reducing the retry count each time, until either I get a successful result or exhaust all retries.

  • If all retries fail, I log a final error message and rethrow the AggregateError so it can be handled further if needed.

AggregateError simplifies error handling when you’re dealing with multiple failures at once, especially in asynchronous code. It’s one of those features that might not seem necessary until you run into a situation where it saves you a ton of headaches.

Without AggregateError

To illustrate the usefulness of AggregateError, I’ll show how handling multiple promise rejections without it can be cumbersome and less efficient. Here’s how you might handle this situation without AggregateError

When Promise.any() rejects, I don’t have an AggregateError to easily access all the errors. Instead, I loop through the original promises and individually check which ones failed by attempting to await them again, logging each failure.

If you don’t use AggregateError, you might have to throw and handle each error individually, which complicates the error-handling logic.

Problems Without AggregateError

  • Limited Feedback: The function stops at the first error, so the user only sees one error message at a time. This can be frustrating for users, as they have to fix one issue and submit the form again to see the next error.
  • Cumbersome Code: Handling each error individually requires repetitive code if you want to collect and display all errors at once.

With AggregateError

With AggregateError, error handling is centralized and simplified. It automatically collects all the rejections, allowing you to manage them in a more structured way by grouping multiple errors instead of dealing with each one separately.


Benefits of Using AggregateError

  • Consolidated Error Reporting: All validation errors are collected and thrown together. The user gets feedback on all issues at once, which improves the user experience.
  • Simpler Error Handling: Instead of handling multiple individual errors, you only need one try/catch block to handle them all.
  • Complete Debugging Information: The AggregateError contains a list of all the errors, making it easier to debug and understand what went wrong.

Using AggregateError to group multiple errors has several advantages. It’s especially helpful when multiple things can go wrong at once, like during form validation or parallel API requests.


Found this article helpful? You might enjoy my free newsletter. I share dev tips and insights to help you grow your coding skills and advance your tech career.

Interested in supporting this blog in exchange for a shoutout? Get in touch.


Liked this post?

Check out these related articles that might be useful for you. They cover similar topics and provide additional insights.

Javascript
4 min read

JavaScript Import Attributes (ES2025)

Understanding the new import attributes syntax and why we can't rely on file extensions alone

Nov 10, 2024
Read article
Javascript
3 min read

navigator.clipboard - The New Asynchronous Clipboard API in JavaScript

Copy and paste text, images, and files using the new navigator.clipboard API

Dec 7, 2024
Read article
Javascript
4 min read

Understanding Bitwise Shifts in JavaScript: << and >>

A practical guide to left and right shift operators in JavaScript

Nov 12, 2024
Read article
Javascript
6 min read

Understanding JavaScript Closures With Examples

Closures are essential for creating functions that maintain state, without relying on global variables.

Sep 6, 2024
Read article
Javascript
4 min read

Promise.try: Unified Error Handling for Sync and Async JavaScript Code (ES2025)

Stop mixing try/catch with Promise chains - JavaScript's new Promise.try handles return values, Promises, and errors uniformly

Nov 10, 2024
Read article
Javascript
5 min read

Precise Decimal Math in JavaScript with Fraction.js

How to handle exact decimal calculations in JavaScript when floating-point precision isn't good enough

Nov 16, 2024
Read article
Javascript
4 min read

JavaScript compile hints: what they are and when to use them

V8's compile hints let you control which JavaScript gets compiled immediately during page load

May 12, 2025
Read article
Javascript
6 min read

setImmediate() vs setTimeout() in JavaScript

both setImmediate() and setTimeout() are used for scheduling tasks, but they work differently.

Sep 8, 2024
Read article
Javascript
7 min read

JavaScript Sets and Maps: Beyond Arrays and Objects

How to handle unique values and key-value pairs properly without type coercion and performance issues

Nov 17, 2024
Read article

This article was originally published on https://www.trevorlasn.com/blog/aggregate-error-in-javascript. It was written by a human and polished using grammar tools for clarity.