Sub topic 13
Last-Resort Global Error Handlers
This chapter assumes you know how try/catch works, how promise rejections reach .catch(), and how to run a script in the browser console or with Node.js.
Some errors escape every try/catch and .catch() in your program. One example is a throw inside a setTimeout callback. Another is a promise that rejects when nobody attached a handler. JavaScript lets you register global handlers that run when this happens. They exist so you can log the failure and report it. They do not make the program safe to continue.
What Counts as "Uncaught"
An error is uncaught when it travels all the way up the call stack and no catch stops it. A rejection is unhandled when a promise rejects and no rejection handler is attached to it by the end of the current turn of the event loop. The runtime then gives the error to the global handlers.
Browser Handlers
In the browser you listen for two events on window:
window.addEventListener('error', (event) => {
console.error('Uncaught error:', event.error);
});
window.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled rejection:', event.reason);
});
setTimeout(() => {
throw new Error('boom');
}, 0);
Promise.reject(new Error('nobody caught me'));The error event exposes the thrown value as event.error, along with event.message, event.filename, and event.lineno. The unhandledrejection event exposes the rejection value as event.reason. If you call event.preventDefault() in either handler, the browser does not print its usual console message. The page keeps running in both cases.
Node.js Handlers
Node.js emits matching events on process. Save this as global.js and run node global.js:
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection:', reason);
});
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
process.exit(1);
});
Promise.reject(new Error('nobody caught me'));
setTimeout(() => {
throw new Error('boom');
}, 10);The rejection is logged first. Then the timer callback throws, the uncaughtException handler logs it, and the process exits with code 1.
The call to process.exit(1) matters. Once you add an uncaughtException listener, Node no longer crashes on uncaught errors. By the time the handler runs, the error has interrupted some operation partway through. Files may be half-written, locks may still be held, and objects may be in an inconsistent state. The safe response is to log, flush what you can, and exit, then let a process manager such as systemd, Docker, or Kubernetes start a fresh process.
Common Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Using the global handler instead of local `catch` | You lose context and cannot recover where it matters | Handle expected failures near their source |
| Not exiting after `uncaughtException` in Node | The process keeps running in a corrupted state | Log, then call `process.exit(1)` |
| Swallowing rejections silently in `unhandledRejection` | Bugs disappear without a trace | Log to your monitoring service, and consider exiting |
| Assuming unhandled rejections are harmless | Since Node 15, an unhandled rejection with no listener crashes the process | Attach `.catch()` or `await` inside `try` |
Exercise
A Node.js server registers process.on('uncaughtException', (err) => console.error(err)) and nothing else. A request handler throws inside a timer callback. What happens, and what should the handler do differently?
Show answer
The error is logged and the process keeps running, because the listener replaces Node's default crash. The interrupted request may have left state inconsistent (open resources, partial writes). After logging, the handler should call process.exit(1) so a process manager can restart a clean process.
Exercise
In the browser, does calling event.preventDefault() in an unhandledrejection listener fix the rejected promise?
Show answer
No. It only stops the browser from printing its default console warning. The promise stays rejected, and the code that depended on it still did not get a value.