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).
// 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; });2Practical Example
Here is a real-world application of Async Error Handling showing how it is used in production JavaScript code.
// 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);
});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).
// 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; });