The Last Line of Defence
Sometimes errors occur in places you didn't wrap in try..catch. A global error handler catches everything else.
window.onerror = function(message, url, line, col, error) {
console.log('Uncaught error!');
console.log('Message:', message);
console.log('File:', url, 'Line:', line);
// Send to your error tracking service
sendToErrorTracker({ message, url, line, stack: error?.stack });
return true; // Prevents the browser from printing it to console
};
For Unhandled Promise Rejections
window.addEventListener('unhandledrejection', function(event) {
console.error('Unhandled Promise rejection:', event.reason);
sendToErrorTracker({ reason: event.reason });
});
Real-World Purpose
In production, these handlers send error reports to monitoring services like Sentry or Datadog, alerting developers when users encounter bugs — even bugs the developer never personally saw.
Caution
Global handlers don't FIX errors — they only report them. Treat every alert from them as a real bug that needs to be fixed in code. Never use them as a substitute for proper local error handling.