Intermediate LevelJavaScript & TypeScript
How does error handling work in async JavaScript (try/catch, Promise .catch, global unhandledrejection)?
❓ Interview Prompt: Explain error propagation in promises, async/await try/catch, custom Error subclasses, and unhandledrejection event listeners.
Error handling in asynchronous code requires dedicated patterns because async errors occur outside the call stack of the initiating function:
Error Propagation Rules:
1
Promises: Uncaught errors inside a Promise executor automatically trigger the
.catch() handler.2
`async/await`: Rejections throw an exception that must be caught using
try...catch.3
Global Safety Net: Uncaught promise rejections trigger the
unhandledrejection window event in browsers or process event in Node.js.Code Implementation Example
javascript
// Custom Domain Error
class ApiError extends Error {
constructor(status, message) {
super(message);
this.status = status;
this.name = 'ApiError';
}
}
// Global Safety Net for uncaught promise rejections
window.addEventListener('unhandledrejection', (event) => {
console.error('UNCAUGHT PROMISE REJECTION:', event.reason);
});
async function fetchData() {
try {
throw new ApiError(404, 'Resource not found');
} catch (err) {
if (err instanceof ApiError) {
console.log(`API Error ${err.status}: ${err.message}`);
} else {
throw err; // Re-throw unexpected errors
}
}
}💡Custom error classes, try/catch type checking, and global unhandledrejection listening.
🎯 Interview Key Takeaway
Always handle promise rejections with try/catch or .catch(). Register unhandledrejection listeners as a global safety net.
#Error Handling#Async#Promises#Intermediate
Back to all JavaScript & TypeScript Questions→