Advertisement
Advanced JavaScript, Error Handling

How do global error handlers like window.onerror and unhandledrejection work?

Short answer

window.addEventListener('error', ...) catches uncaught synchronous exceptions bubbling up to the top; window.addEventListener('unhandledrejection', ...) catches Promise rejections that were never handled by a .catch().

Save JavaScript mock interview
Advertisement
AModel answer
window.addEventListener('error', ...) catches uncaught synchronous exceptions bubbling up to the top; window.addEventListener('unhandledrejection', ...) catches Promise rejections that were never handled by a .catch(). Together they form a last-resort safety net for logging errors that slipped past local handling.
window.addEventListener('unhandledrejection', (event) => {
  console.error('Unhandled rejection:', event.reason);
  event.preventDefault(); // suppress default browser logging
});
Real-world example
Reporting any error that slips through the app's normal handling to a monitoring service like Sentry.
Likely follow-ups
  • Should you rely on these global handlers instead of local try/catch blocks?
Related topics