Up to date
Published
Updated on
6 min read

Trevor I. Lasn

Building tools for developers. Currently building courses.reviews and blamesteve.lol

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.


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

Javascript
7 min read

JavaScript Truthy and Falsy: A Deep Dive

Grasp JavaScript's type coercion with practical examples and avoid common pitfalls

Oct 27, 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
3 min read

Float16Array in JavaScript

Understanding the new 16-bit floating point array in JavaScript

Apr 14, 2025
Read article
Javascript
4 min read

Intl.DurationFormat: Format Time Durations with Locale Support

Stop writing manual duration formatting code. Instead, leverage the new powerful Intl.DateTimeFormat API for internationalized time displays

Mar 13, 2025
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
4 min read

What is the JavaScript Pipeline Operator |>

A deep dive into how pipeline operators can make your code more readable and maintainable

Oct 29, 2024
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
Javascript
5 min read

Working with JavaScript's Scheduler API

Learn how to prioritize and control task execution in JavaScript using the new Scheduler API for better performance and user experience

Nov 26, 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.