🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

Async Error Handling

AI & DATA SCIENCE // async-error

Handle async errors with try/catch around await, or .catch() on Promises. Unhandled rejections crash Node.js and warn in browsers.

Syntax

async function fn() {
  try {
    await riskyOperation();
  } catch (e) {
    handleError(e);
  }
}

Deep Dive Course

Async errors that aren't caught become **unhandled Promise rejections**. In Node.js 15+, unhandled rejections crash the process. In browsers, they trigger a `unhandledrejection` event. Always handle async errors with try/catch in async functions or `.catch()` on raw Promises.

1Understanding Async Error Handling

Async errors that aren't caught become unhandled Promise rejections. In Node.js 15+, unhandled rejections crash the process. In browsers, they trigger a unhandledrejection event. Always handle async errors with try/catch in async functions or .catch() on raw Promises.

💡

Add a global unhandledrejection listener as a safety net: window.addEventListener('unhandledrejection', handler).

editor.html
// Different ways to handle async errors

// 1. try/catch with await
async function loadUser(id) {
  try {
    const user = await fetchUser(id);
    return user;
  } catch (e) {
    if (e.status === 404) return null; // handle 404
    throw e; // re-throw other errors
  }
}

// 2. .catch() on Promise
fetchUser(id)
  .then(showUser)
  .catch(e => { if (e.status !== 404) throw e; });
localhost:3000

2Practical Example

Here is a real-world application of Async Error Handling showing how it is used in production JavaScript code.

editor.html
// Global unhandled rejection handler (safety net)
window.addEventListener('unhandledrejection', event => {
  console.error('Unhandled:', event.promise, event.reason);
  event.preventDefault(); // prevent console error
});

// Node.js equivalent
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled rejection:', reason);
});
localhost:3000

3Best Practices

Follow these guidelines when working with Async Error Handling:

1. Wrap await calls in try/catch

2. Add .catch() to all raw Promise chains

3. Add a global unhandledrejection handler as fallback

⚠️

Tip: Add a global unhandledrejection listener as a safety net: window.addEventListener('unhandledrejection', handler).

editor.html
// Different ways to handle async errors

// 1. try/catch with await
async function loadUser(id) {
  try {
    const user = await fetchUser(id);
    return user;
  } catch (e) {
    if (e.status === 404) return null; // handle 404
    throw e; // re-throw other errors
  }
}

// 2. .catch() on Promise
fetchUser(id)
  .then(showUser)
  .catch(e => { if (e.status !== 404) throw e; });
localhost:3000

Examples

Example 01Basic Usage
// Different ways to handle async errors

// 1. try/catch with await
async function loadUser(id) {
  try {
    const user = await fetchUser(id);
    return user;
  } catch (e) {
    if (e.status === 404) return null; // handle 404
    throw e; // re-throw other errors
  }
}

// 2. .catch() on Promise
fetchUser(id)
  .then(showUser)
  .catch(e => { if (e.status !== 404) throw e; });
Example 02Advanced Example
// Global unhandled rejection handler (safety net)
window.addEventListener('unhandledrejection', event => {
  console.error('Unhandled:', event.promise, event.reason);
  event.preventDefault(); // prevent console error
});

// Node.js equivalent
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled rejection:', reason);
});

Best Practices

  • Wrap await calls in try/catch
  • Add .catch() to all raw Promise chains
  • Add a global unhandledrejection handler as fallback

Interview Question

What is an unhandled Promise rejection?

Hint: A Promise that rejects with no .catch().

An unhandled Promise rejection occurs when a Promise rejects and there's no .catch() handler or try/catch in an async function to handle it. In Node.js 15+, this crashes the process. In browsers, it triggers the 'unhandledrejection' window event. Always ensure every Promise chain has error handling.

Exercises

MediumPractice using Async Error Handling in a real scenario.
View Solution
// Different ways to handle async errors

// 1. try/catch with await
async function loadUser(id) {
  try {
    const user = await fetchUser(id);
    return user;
  } catch (e) {
    if (e.status === 404) return null; // handle 404
    throw e; // re-throw other errors
  }
}

// 2. .catch() on Promise
fetchUser(id)
  .then(showUser)
  .catch(e => { if (e.status !== 404) throw e; });

Frequently Asked Questions

What is an unhandled Promise rejection?

An unhandled Promise rejection occurs when a Promise rejects and there's no .catch() handler or try/catch in an async function to handle it. In Node.js 15+, this crashes the process. In browsers, it triggers the 'unhandledrejection' window event. Always ensure every Promise chain has error handling.

Related Functions

Promisesawaittrycatchcatch

Want to go deeper?

See JAVASCRIPT in action across a full course, not just this reference entry.

Explore the JAVASCRIPT course →