Global Error Handlers
What you'll learn: How to set up last-resort error handlers that catch otherwise unhandled errors in both browser and Node.js environments.
Sometimes errors slip through your try/catch blocks, or they occur in parts of your code you didn't anticipate. Global error handlers act as a safety net—they're the last line of defense that catches errors before they crash your application or disappear silently.
Think of global error handlers like emergency services: you hope you never need them, but when something goes wrong that wasn't handled locally, they're there to log the problem, alert you, or attempt graceful recovery.
In the Browser: window.onerror
In browser JavaScript, you can assign a function to window.onerror that will be called whenever an uncaught error occurs:
window.onerror = function(message, source, lineno, colno, error) {
console.error('Global error caught:', message);
console.error('Location:', source, 'Line:', lineno);
// Log to monitoring service, show user-friendly message, etc.
return true; // Prevents default error handling
};
In Node.js: Process-Level Handlers
Node.js provides process event handlers for uncaught exceptions and unhandled promise rejections:
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
// Log error, cleanup, then exit
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Promise Rejection:', reason);
// Log for investigation
});
When to Use Them
Global handlers are not a replacement for proper error handling. Use them for:
- Logging errors you didn't anticipate
- Monitoring production issues
- Graceful shutdown in Node.js
- Displaying user-friendly error pages
Always handle errors locally when possible—global handlers are your emergency backup.
Key Takeaway: Global error handlers like window.onerror, uncaughtException, and unhandledRejection catch errors that slip through your regular error handling, providing a last-resort safety net for logging and recovery.