In Node.js, what does registering process.on('uncaughtException') change about a crash, and why is it unsafe to keep serving afterwards?
answer
- default: stack to stderr, then exit
- a listener cancels the default exit
- state after unwinding is unknown
- log synchronously, clean up, exit non-zero
- monitor event observes without cancelling
basics
~20 sA process 'uncaughtException' listener replaces Node's default of printing the stack trace and exiting with code 1, so the process keeps running. Its state is now unknown, so the handler should log synchronously, clean up and exit non-zero.
solid answer
~40 sWith no listener, an exception that bubbles back to the event loop makes Node print the stack trace to stderr and exit with code 1, overriding any `process.exitCode` set earlier. Registering `process.on('uncaughtException', handler)` removes that default: the process keeps running, and if it later exits on its own it uses `process.exitCode`, which means 0 unless you set it. The Node docs call the event a crude, last-resort mechanism: the exception unwound through code that never finished, so half-applied updates, held resources and open handles may be inconsistent, and resuming normal operation is explicitly not safe. The correct use is synchronous logging and cleanup, then a non-zero exit, with an external supervisor restarting the process. To observe crashes without changing them, listen on `uncaughtExceptionMonitor` instead.
code
javascript · 11 linesimport { writeSync } from 'node:fs';
import process from 'node:process';
process.on('uncaughtException', (err, origin) => {
writeSync(process.stderr.fd, `fatal (${origin}): ${err?.stack ?? err}\n`);
process.exit(1);
});
setTimeout(() => {
JSON.parse('{not json');
}, 10);go deeper
Recall the default: stack trace on stderr and exit code 1. Then say plainly that adding a listener stops that exit, and why that is dangerous rather than helpful.
Explain what a listener changes in each case: logging and returning, setting process.exitCode, throwing inside it, and using uncaughtExceptionMonitor instead.
Show the production consequences of resuming: leaked handles, hung requests, corrupted in-memory state. Describe a synchronous log, a non-zero exit and an external restart as the policy.
Frame the handler as a team-wide contract: one shared crash module, observe with the monitor, always exit, and rely on the supervisor for availability rather than on surviving bugs in-process.
## What Node does when nothing catches an exception An **uncaught exception** is a JavaScript exception that bubbles all the way back to the Node.js event loop: a `throw` inside a timer callback, an I/O callback or an event listener, with no `try...catch` on the way. Because the loop called that callback, there is no caller left to catch it. Node's default handling is fixed and short: - it prints the error's stack trace to `stderr`; - it exits the process with **exit code 1**, overriding any `process.exitCode` the program had set earlier; - before dying it emits `uncaughtExceptionMonitor` and, with no handler present, the `'exit'` event with code 1. Two other routes land in the same place. An `EventEmitter` that emits `'error'` with no `'error'` listener throws that error, and under Node 24's default `--unhandled-rejections=throw` mode an unhandled promise rejection with no `unhandledRejection` listener is raised as an uncaught exception too, arriving with the `origin` argument set to `'unhandledRejection'` rather than `'uncaughtException'`. ## What a listener changes Registering a listener for `'uncaughtException'` overrides the default. Node calls `handler(err, origin)` and then carries on running the event loop. The table shows the outcomes worth knowing. | Setup | What happens | Exit code | |---|---|---| | No listener | Stack trace printed, process exits | 1 | | Listener that logs and returns | Process keeps running until the loop empties or code calls `process.exit()` | 0, or `process.exitCode` | | Listener sets `process.exitCode = 1` and returns | Still keeps running; a listening server keeps it alive indefinitely | 1, when it finally exits | | Listener that throws | Not caught again; stack printed, process exits | 7 | | Only an `uncaughtExceptionMonitor` listener | Error observed, default crash still happens | 1 | The fourth row exists to avoid infinite recursion: an exception thrown inside the handler is not fed back to it. ## Why resuming is unsafe The Node docs are blunt: `'uncaughtException'` should not be used as an equivalent of "On Error Resume Next", and **it is not safe to resume normal operation** after it. The reason is what the exception skipped while it unwound: - an update to shared in-memory state may be half applied, with a counter incremented and the matching record never written; - a lock, a pooled connection or a file descriptor acquired before the throw may never be released; - callbacks other requests are waiting on may now never be called, so those requests hang instead of failing; - the code that threw has no idea it is being "recovered", so nothing re-establishes its invariants. The docs compare it to pulling out the power cord while upgrading a computer: nine times out of ten nothing happens, and the tenth time the system is corrupted. A service that keeps serving after such an error trades one visible crash for an unknown number of silent wrong answers. ## The correct handler The supported use of the event is a short, synchronous goodbye: 1. **Log the error synchronously.** `fs.writeSync(process.stderr.fd, ...)` is what the Node docs use; an asynchronous logger may never flush once you exit. 2. **Release what must be released synchronously**, for example a lock file or a PID file. 3. **Exit with a non-zero code** so whoever watches the process sees a failure. 4. **Let a separate process restart it.** The docs recommend an external monitor to detect failures and restart, whether or not the event was emitted. Keep asynchronous work out of the handler. A network call to an error service, or a logger that buffers and flushes later, may never complete once you exit, and waiting for it keeps a process in an unknown state alive. If one asynchronous step is essential, bound it with a timer and exit regardless of its outcome. Separately, when a core file is more useful than a log line, the `--abort-on-uncaught-exception` flag makes Node abort rather than exit, so a debugger can inspect the state post mortem; that is a diagnostics choice, not a recovery mechanism. ## Observing without overriding `uncaughtExceptionMonitor` is emitted before `'uncaughtException'` with the same `(err, origin)` arguments, and installing it **does not change the behaviour**: without an `'uncaughtException'` listener the process still crashes. It is the right hook for an error reporter that should see the crash but must not prevent it. A third mechanism, `process.setUncaughtExceptionCaptureCallback(fn)`, replaces the event entirely while a capture function is set; it is mutually exclusive with the deprecated `domain` module and is rarely what application code wants.
- What does the second argument of an 'uncaughtException' listener tell you?`origin` is the string `'uncaughtException'` for a synchronous throw that reached the loop, or `'unhandledRejection'` when the error came from an unhandled promise rejection under the default `throw` mode or `strict`, or from a rejection during the entry point's ES module static loading phase. It lets one handler log the two failure sources distinctly.
- What happens if the 'uncaughtException' handler itself throws?Node does not call the handler again, which would risk infinite recursion. It prints the new stack trace and exits with code 7, the documented code for an internal exception-handler run-time failure. A handler should therefore wrap its own risky work, such as serialising an odd error object, in `try...catch`.
- When would you use uncaughtExceptionMonitor instead of 'uncaughtException'?When you want to record the crash, for example in an error reporter loaded by a shared library, without changing what the process does. The monitor runs first and leaves the default crash and exit code 1 in place, so a library cannot accidentally turn every fatal error into a silently surviving process.
- An uncaughtException handler is a good way to keep the server up after a bug.
- Node still exits on its own once the uncaughtException handler returns.
- uncaughtExceptionMonitor prevents the crash just like an uncaughtException listener.
- An error thrown inside the handler is caught by the same handler again.
- Setting process.exitCode in the handler stops the process immediately.