Sub topic 13
Last-Resort Global Error Handlers
Earlier chapters covered catching errors where they happen: try/catch around synchronous code, .catch() on promise chains, and try/catch around await. Some errors still get past all of these. A callback can throw after its surrounding try has finished, someone can forget a .catch(), or a library can fail in a way nobody planned for. JavaScript environments offer a final checkpoint for these: global handlers that run when an error reaches the top of the program with nothing left to catch it.
This chapter assumes you can run code in a browser console and in Node.js. It also assumes you know how errors propagate up the call stack and how promise rejections travel down a chain, both covered earlier.
What "Uncaught" Means
An error is uncaught when it propagates out of the outermost function on the call stack and no catch intercepted it on the way. The runtime then has nothing left to hand it to. Promises have their own version of this. A rejection is unhandled when a promise rejects and has no rejection handler attached by the time the runtime checks. That check happens shortly after the current task and its microtasks finish.
These are two separate events, and each environment reports them separately:
| Situation | Browser event | Node.js event |
|---|---|---|
| Synchronous throw escapes to the top (including from timers and event listeners) | `error` on `window` | `uncaughtException` on `process` |
| Promise rejects with no handler | `unhandledrejection` on `window` | `unhandledRejection` on `process` |
| A handler is attached later to an already-reported rejection | `rejectionhandled` on `window` | `rejectionHandled` on `process` |
Browser Handlers
The error event
When a script throws and nothing catches it, the browser dispatches an ErrorEvent on window. The event has message, filename, lineno, colno, and error. The error property holds the thrown value, which is usually an Error with a stack.
window.addEventListener('error', (event) => {
console.log('Message:', event.message);
console.log('Where:', `${event.filename}:${event.lineno}:${event.colno}`);
console.log('Stack:', event.error && event.error.stack);
});
setTimeout(() => {
throw new Error('boom from a timer');
}, 0);The timer callback runs after any surrounding try has already exited, so this error lands in the global handler. The browser also prints its usual red console message. To suppress that message, call event.preventDefault() in the listener. The older window.onerror = function (message, source, lineno, colno, error) { ... } form does the same job when it returns true.
The error event is also used for resources that fail to load, such as a broken <img> or <script>. Those events do not bubble to window, and they are plain Event objects with no message or error. If you want them too, register with { capture: true } and check event.target.
The unhandledrejection event
Rejected promises with no handler produce a PromiseRejectionEvent. Its reason is the rejection value and its promise is the promise that rejected.
window.addEventListener('unhandledrejection', (event) => {
console.log('Unhandled rejection:', event.reason);
event.preventDefault(); // stops the default console warning
});
window.addEventListener('rejectionhandled', (event) => {
console.log('Handled late:', event.reason);
});
const p = Promise.reject(new Error('nobody listened'));
setTimeout(() => {
p.catch(() => {}); // attached too late: triggers rejectionhandled
}, 1000);The reason is not always an Error. Code can call reject('oops') or throw 42. Your handler should cope with any value, for example by logging String(reason) when reason.stack is missing.
Node.js Handlers
uncaughtException
Node's default behavior for an uncaught exception is to print the stack trace and exit with code 1. Registering a process.on('uncaughtException', ...) listener replaces that default, so the process keeps running unless you stop it. That is almost never what you want.
const fs = require('fs');
process.on('uncaughtException', (err, origin) => {
// Use a synchronous write so the message is flushed before exit.
fs.writeSync(2, `Fatal (${origin}): ${err.stack}\n`);
process.exit(1);
});
setTimeout(() => {
JSON.parse('{bad json');
}, 0);The second argument, origin, is 'uncaughtException' for a normal throw, or 'unhandledRejection' when an unhandled rejection was escalated into an exception.
Why the process should exit
When an exception escapes, the code that threw was cut off mid-operation. A file handle may still be open, a lock may still be held, a counter may be half-updated, or a database transaction may be left in an unknown state. Node's documentation states plainly that resuming normal operation after uncaughtException is unsafe. The handler's job is to record what happened and shut down. A process manager such as systemd, PM2, a container orchestrator, or a cluster supervisor then starts a clean process.
Keep the handler short and synchronous. process.exit() ends the process immediately, and pending asynchronous work such as a network request to an error tracker or a buffered stream write may never complete. If you must send something over the network, set process.exitCode = 1 and start a short forced-exit timer instead of calling process.exit() right away:
process.on('uncaughtException', (err) => {
console.error('Fatal:', err);
process.exitCode = 1;
// Give async reporting a moment, then force exit regardless.
setTimeout(() => process.exit(1), 2000).unref();
// reportToTracker(err) would go here
});The .unref() call keeps the timer itself from holding the process open. If nothing else is pending, the process exits right away.
unhandledRejection
Since Node.js 15, the default mode is --unhandled-rejections=throw. An unhandled rejection is raised as an uncaught exception, so it crashes the process unless an unhandledRejection listener exists. Registering a listener means you choose what happens.
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection:', reason);
process.exitCode = 1;
throw reason; // hand it to uncaughtException for the standard shutdown path
});
process.on('uncaughtException', (err, origin) => {
console.error(`Fatal (${origin}):`, err instanceof Error ? err.message : err);
process.exit(1);
});
async function main() {
throw new Error('forgot to await and catch');
}
main(); // no .catch(): rejection is unhandledRethrowing from unhandledRejection routes every fatal failure through one shutdown path. The other flag values are strict (always raise as an exception), warn (only print a warning), warn-with-error-code (warn and set the exit code to 1), and none (stay silent). Don't use warn or none in production to hide problems.
How Global Handlers Fit with Local Handling
Global handlers are a safety net. They are not an error-handling strategy. By the time one runs, you have lost the context that would let you recover. You don't know which request failed, which user to notify, or what to retry. Use them for three things:
- Logging and reporting. Capture the stack and send it to a monitoring tool so the bug gets fixed.
- Graceful shutdown in Node.js. Stop accepting new work, close what you can, and exit.
- User feedback in browsers. Show a generic "something went wrong" message instead of failing silently.
Every entry in these logs points to a missing local handler. The fix is a .catch(), an await inside try, or a guard at the right place in the code. Making the global handler smarter does not fix it.
Common mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Listening for `uncaughtException` without exiting | Process runs on in a corrupted state | Log, then `process.exit(1)` or use `uncaughtExceptionMonitor` |
| Assuming `event.reason` or `err` is an `Error` | Handler crashes on `.stack` of a string | Check `instanceof Error` first |
| Async logging followed by immediate `process.exit()` | Log entry lost | Write synchronously or delay exit with an unref'd timer |
| Relying on `window` `error` for cross-origin scripts | Only "Script error." is recorded | Add CORS headers and `crossorigin` |
| Throwing inside the global handler itself | Recursive failure or hard crash | Keep the handler minimal and defensive |
Exercise
A Node.js server registers process.on('uncaughtException', (err) => console.error(err)) and nothing else. A request handler throws inside a setTimeout callback while holding an in-memory lock. What happens, and what should the handler do instead?
Show answer
The listener replaces Node's default crash, so the error is logged and the process keeps running. The lock is never released, and later requests that need it may hang or see inconsistent state. The handler should log the error (synchronously, or with a bounded delay) and then call process.exit(1), so a process manager can restart a clean instance.
Exercise
In a browser, the code runs Promise.reject(new Error('x')) with no handler, and 500 ms later calls .catch() on that same promise. Which window events fire, and in what order?
Show answer
First unhandledrejection fires, after the current task's microtasks finish and the promise still has no handler. When .catch() is attached 500 ms later, rejectionhandled fires for the same promise. Monitoring code can use the second event to clear the earlier report.
Exercise
Why does Node.js 15 and later crash on an unhandled rejection by default, and what changes once you register an unhandledRejection listener?
Show answer
The default mode is --unhandled-rejections=throw, so an unhandled rejection is raised as an uncaught exception, which crashes the process. Once you register an unhandledRejection listener, that escalation no longer happens. Your listener decides what to do, so it must log the reason and either exit or rethrow to reach the uncaughtException path.