Handling Async Errors

When working with asynchronous JavaScript (Promises, async/await), errors don't behave like synchronous code. Handling these errors correctly is vital to avoid unhandled rejections and bugs.

Common Ways to Handle Async Errors

  • Using .catch() with Promises: Attach a catch method to handle rejected Promises.
  • Try–Catch with async/await: Wrap await calls inside try blocks and handle errors in catch.
Promise vs Async/Await Error Handling
ApproachError Handling
Promise promiseFunction().then(...).catch(error => ...)
Async/Await try { await asyncFunction(); } catch(error) { ... }

📌 Deep Dive: Handling Errors with async/await

JAVASCRIPT
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error.message);
  }
}

fetchData();
Output
Fetch error: Network response was not ok (if fetch fails)

📌 Deep Dive: Handling Errors with Promises and catch

JAVASCRIPT
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Fetch error:', error.message));
Output
Fetch error: Network response was not ok (if fetch fails)
Illustration of handling_async_errors
Illustration of handling_async_errors

💡 Important:

Always handle errors explicitly. Unhandled Promise rejections often lead to silent failures and hard-to-debug issues.

⚠️ Common Pitfall:

Do NOT forget to use await inside try when using async/await. Missing await causes errors to be unhandled outside.

Handling Multiple Async Errors

When awaiting multiple Promises, use Promise.allSettled() to handle all results including errors without failing fast:

📌 Deep Dive: Using Promise.allSettled()

JAVASCRIPT
const promises = [
  Promise.resolve('Success 1'),
  Promise.reject(new Error('Failure 2')),
  Promise.resolve('Success 3')
];

Promise.allSettled(promises).then(results => {
  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`Promise ${index + 1} succeeded with`, result.value);
    } else {
      console.error(`Promise ${index + 1} failed with`, result.reason);
    }
  });
});
Output
Promise 1 succeeded with Success 1
Promise 2 failed with Error: Failure 2
Promise 3 succeeded with Success 3

💡 Summary:

  • Use .catch() for Promise error handling and try/catch when using async/await.
  • Always check for response errors explicitly (e.g., response.ok).
  • For multiple Promises, Promise.allSettled() helps handle all results safely.