Skip to main content

Smarter Error Handling in JavaScript: Group, Don’t Panic



My async code used to feel like a tangle of errors I couldn’t unravel quickly. Each failed promise would spit out its own error, leaving me to stitch together a solution.

Then I discovered AggregateError, and it changed how I debug. It’s a JavaScript feature that bundles multiple errors into one object, perfect for complex async tasks.

Imagine validating a form where multiple fields are checked asynchronously. Without AggregateError, you’re stuck catching each error separately, which bloats your code and confuses users. It’s a slog to debug and deliver clear feedback.

The Old, Clunky Way

Without AggregateError, you’d handle each validation error individually. It’s tedious and error-prone.

const fetchFromApi1 = () => Promise.reject(new Error('API 1 failed'));
const fetchFromApi2 = () => Promise.reject(new Error('API 2 failed'));
const fetchFromApi3 = () => Promise.reject(new Error('API 3 failed'));
async function fetchWithoutAggregateError(apis, retries = 3, delay = 1000) {
try {
const data = await Promise.any(apis);
console.log('Data fetched:', data);
return data;
} catch (e) {
console.log('All promises failed.');
    // Manually handle each promise rejection by checking which promises failed
for (let i = 0; i < apis.length; i++) {
try {
await apis[i];
} catch (error) {
console.log(`Error from API ${i + 1}:`, error.message);
}
}
    if (retries > 0) {
console.log(`Retrying... (${retries} attempts left)`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithoutAggregateError(apis, retries - 1, delay);
} else {
console.log('All data sources failed after multiple attempts. Please try again later.');
throw new Error('All data sources failed after retries.');
}
}
}
// Start fetching data with retries
fetchWithoutAggregateError([fetchFromApi1(), fetchFromApi2(), fetchFromApi3()]);

This approach requires a try/catch for each check. It’s repetitive and hard to maintain.

function validateUserWithoutAggregateError(user) {
if (!user.name) {
throw new Error('Name is required');
}
if (!user.email) {
throw new Error('Email is required');
}
if (user.age < 18) {
throw new Error('User must be at least 18 years old');
}
    return true;
}
try {
validateUserWithoutAggregateError({ name: '', email: '', age: 17 });
} catch (e) {
console.log(e.message); // Only the first error is caught and displayed
// Output: "Name is required"
}

🔴 Multiple try/catch blocks clutter your code.
🔴 Users get fragmented error messages, hurting their experience.

Here’s how to do it

When Promise.any() looks for the first resolved promise and all promises reject, JavaScript raises an AggregateError. This error collects all rejection reasons into a single object.

const fetchFromApi1 = () => Promise.reject(new Error('API 1 failed'));
const fetchFromApi2 = () => Promise.reject(new Error('API 2 failed'));
const fetchFromApi3 = () => Promise.reject(new Error('API 3 failed'));
async function fetchWithRetry(apis, retries = 3, delay = 1000) {
try {
const data = await Promise.any(apis);
console.log('Data fetched:', data);
return data;
} catch (e) {
if (e instanceof AggregateError) {
console.log(e.name); // "AggregateError"
console.log(e.message); // "All promises were rejected"
console.log('Errors:', e.errors); // [Error: API 1 failed, Error: API 2 failed, Error: API 3 failed]
      if (retries > 0) {
console.log(`Retrying... (${retries} attempts left)`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(apis, retries - 1, delay);
} else {
console.log('All data sources failed after multiple attempts. Please try again later.');
throw e; // Re-throw the error after exhausting retries
}
} else {
// If the error is not an AggregateError, rethrow it
throw e;
}
}
}
// Start fetching data with retries
fetchWithRetry([fetchFromApi1(), fetchFromApi2(), fetchFromApi3()]);
  • When using Promise.any() to fetch data from multiple APIs, it resolves with the first successful response. If all promises reject, it raises an AggregateError.
  • Wrap the operation in a try/catch block: the try block processes successful data, while the catch block captures the AggregateError when all promises fail.
  • If an AggregateError occurs, I log its details and retry the operation up to a set number of attempts, adding a delay between each try.
  • Retry logic works by recursively calling the function, decrementing the retry count each time, until a success occurs or all retries are exhausted.
  • If retries run out, I log a final error message and rethrow the AggregateError for further handling if needed.

AggregateError streamlines managing multiple async failures, making complex error handling cleaner. It’s a tool you’ll appreciate when debugging chaotic async flows.

function validateUser(user) {
let errors = [];
    if (!user.name) {
errors.push(new Error('Name is required'));
}
if (!user.email) {
errors.push(new Error('Email is required'));
}
if (user.age < 18) {
errors.push(new Error('User must be at least 18 years old'));
}
    if (errors.length > 0) {
throw new AggregateError(errors, 'Validation failed');
}
    return true;
}
try {
validateUser({ name: '', email: '', age: 17 });
} catch (e) {
if (e instanceof AggregateError) {
console.log(e.name); // "AggregateError"
console.log(e.message); // "Validation failed"
e.errors.forEach(err => console.log(err.message));
// Output:
// "Name is required"
// "Email is required"
// "User must be at least 18 years old"
}
}

This code runs all checks and collects errors in one shot. You can show users a clear list of issues without extra logic.

✅ Consolidates errors for cleaner code.
✅ Makes form validation logic easier to manage.
✅ Delivers clear feedback to users, fast.

Final Takeaway

AggregateError turns chaotic error handling into a smooth process. It’s a game-saver for form validation or any async task with multiple points of failure. Give it a spin in your next form-heavy app.

Follow me for more error-handling tricks!

Comments

Popular posts from this blog

CSS only Click-handlers You Might not be using, but you should

  You’re building a simple website, a good-looking landing page with a “See More” button. Instinctively, you reach for JavaScript to handle the button click event. But wait — what if I told you that CSS alone could do the job? Yes. CSS is often underestimated, but it can handle click interactions without JavaScript. In this guide, you’ll learn how to create CSS-only click handlers using the :target pseudo-class, and explore scenarios where this approach makes perfect sense. The :target Pseudo-Class CSS offers several pseudo-classes that let you style elements based on different states ( :hover , :focus , :checked ). But there’s one you might not have used before —  :target . The :target pseudo-class applies styles to an element when its ID matches the fragment identifier in the URL (the part after # ). This behavior is commonly seen when clicking an anchor link that jumps to a section on the same page. Here’s a simple example : <a href="#contact">Go to Contact</...

Sharpen Your Front-End Skills: Quick HTML, CSS & React Interview Challenges

  The source of this image is Chat GPT based on writing! Are you preparing for front-end developer interviews and looking for practical, hands-on ways to improve your HTML, CSS, and React skills? Whether you’re a beginner aiming to build confidence or an experienced developer brushing up on UI skills, small, targeted challenges can make a huge difference. In this article, I’ll walk you through some of the best free and low-cost resources that offer real-world front-end tasks — perfect for interview prep, portfolio building, and daily practice. 1. Frontend Mentor frontendmentor.io Frontend Mentor is one of the most popular platforms for hands-on HTML, CSS, and JavaScript challenges. You get beautifully designed templates (in Figma or image formats) and are asked to bring them to life using clean code. The platform offers difficulty levels ranging from newbie to expert, and it’s perfect for practicing responsiveness and semantic HTML. Bonus : You can even filter for React-based ...

6 Essential JavaScript Concepts Every Developer Should Understand

It’s the only language I’ve used where [] == ![] it's true and where you can, typeof null and somehow get 'object' . But despite all its quirks (and there are many), there are a few core concepts that make life with JS not just easier, but saner. This isn’t some computer science flex. These are practical concepts that, once you understand them, make you write better, cleaner, and less buggy code. 1. Hoisting  Before you rage at your variables being undefined , understand this: JS hoists variable and function declarations to the top of their scope. But —  and this is important  —  only the declarations , not the assignments. Why? Because JS reads it like: This is also why let and const behave differently — they’re hoisted too, but live in the “Temporal Dead Zone” until declared. 2. Closures Closures are like little memory vaults for your functions. They allow functions to remember variables from the scope they were created in, even after that scope has gone. Why care? T...