Handling uncaught errors and rejections

Intermediate · 13 min

What Node does with uncaught exceptions and unhandled rejections, operational versus programmer errors, and a last-resort handler that logs and exits.

Before thisCancellation with AbortControllerThe process object

Software Developer Diaries · 13 min

Handling uncaught errors and rejections

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Software Developer DiariesReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An exception nobody catches triggers `process.on('uncaughtException')`, and with no listener Node prints the stack and exits with code 1.
  • A rejected promise nobody handles triggers `unhandledRejection`. Since Node 15 the default mode is `throw`, which turns it into an uncaught exception that also exits the process.
  • `--unhandled-rejections=warn` or `none` restore the old keep-running behaviour. Use them only as a stopgap, since the program continues in an unknown state.
  • Operational errors (a refused connection, bad user input, a full disk) are expected and handled where they occur. Programmer errors (a `TypeError` from a bug) mean the process state is suspect.
  • A last-resort handler should log, start a bounded graceful shutdown, and exit non-zero so a supervisor restarts the process. It should not try to carry on.

Two ways errors escape

Normally you handle an error near where it happens, with try/catch, a promise .catch, or an error-first callback. When none of those catch it, the error escapes in one of two ways.

An uncaught exception is a throw that unwinds to the top of the stack with no catch. Common sources are a bug in a timer callback or an EventEmitter that emits 'error' with no listener. Node prints the stack and exits with code 1.

An unhandled rejection is a promise that rejected with no .catch or await attached by the time the microtask queue drained. These are how a forgotten await looks, as in saveAudit(user) with no await and no handler.

I ran a one-line script, Promise.reject(new Error("boom")) plus a timer, on Node 26. Default: stack printed, exit 1, timer never runs.

The modes for rejections

Node 15 changed the default from “warn and keep going” to throw. You can still choose:

--unhandled-rejections= Behaviour
throw (default) Emit unhandledRejection; if no listener, raise as uncaught exception
strict Raise as uncaught exception even if a listener exists
warn Print a warning, emit the event, keep running
warn-with-error-code Like warn, but set exit code 1
none Silence

With warn my script printed an UnhandledPromiseRejectionWarning, ran the timer (“still alive”) and exited 0. Treat warn and none as a migration aid, not a setting to leave on: a program that swallows rejections keeps running with failed work that nobody noticed.

Operational versus programmer errors

Not all errors deserve the same response.

  • Operational errors are failures in a correct program: ECONNREFUSED, a 503 from an upstream service, invalid input, a timed-out query. They are expected. Handle them locally: retry, return a 4xx or 5xx, degrade.
  • Programmer errors are bugs: TypeError: x is not a function, a missing await, an assertion that failed. There is no sensible local recovery, and continuing hides the bug.

The practical rule: catch operational errors precisely where you can act on them, and let programmer errors bubble to the top. The top is where the last-resort handlers live. For how errors are shaped in the language, see error handling and custom errors.

A last-resort handler

import { createServer } from 'node:http';

const server = createServer((req, res) => res.end('ok')).listen(0);

function fatal(err, origin) {
  console.error('fatal', origin, err.message); // use your real logger
  server.close(() => process.exit(1));          // stop accepting, let in-flight finish
  server.closeAllConnections?.();               // don't wait on idle keep-alives
  setTimeout(() => process.exit(1), 5000).unref(); // hard stop if shutdown stalls
}

process.on('uncaughtException', fatal);
process.on('unhandledRejection', (reason) => { throw reason; }); // promote to uncaught

I ran this with a Promise.reject(new Error('promoted')): it logged fatal uncaughtException promoted and exited with code 1. The rules baked in: log first, bound the shutdown with a timer, and exit non-zero so the supervisor (systemd, PM2, Kubernetes) restarts you. Keep the handler small and synchronous where possible, since the process is already in trouble.

If you only want to observe, process.on('uncaughtExceptionMonitor', (err, origin) => ...) fires before the crash without preventing it. Use it for metrics or crash reports.

What the video covers

Software Developer Diaries’ August 2023 video lists central error handling, graceful process exits and extending JavaScript’s Error object. That lines up with the operational-versus-programmer split and the last-resort handler here. I could not read a transcript, so I can’t confirm it covers the --unhandled-rejections modes or the uncaughtExceptionMonitor event; the table and the monitor event above are this page’s.

Where this fits

Last-resort handlers are the bottom layer. In an HTTP service, framework-level error handlers sit above them: see Express error handling. The graceful-shutdown part continues in deploying Node applications. The process object is where the events and exit codes live.

Check yourself

  1. 01A background `fetch` rejects and nothing awaits it. What happens on Node 26 with default settings?

    The rejection is unhandled, Node raises it as an uncaught exception (the `throw` mode), prints the error, and exits with code 1. If you registered an `unhandledRejection` listener, that runs instead and the process keeps going unless you exit or rethrow.

  2. 02Why should an `uncaughtException` handler normally end with an exit instead of continuing?

    After an uncaught exception the code that was running never finished, so locks, half-written state or open resources may be inconsistent. The process can no longer be trusted. Log it, finish what you safely can, exit non-zero, and let a supervisor start a clean process.

  3. 03How do operational and programmer errors differ, and why does it matter?

    Operational errors come from outside your code's control, like ECONNREFUSED or invalid input, and you plan for them with retries, validation and status codes. Programmer errors are bugs, like calling `undefined`. You handle the first kind and fix the second, because recovering in place from a bug hides it.

  4. 04What does `process.on('uncaughtExceptionMonitor')` give you that `uncaughtException` does not?

    It observes the exception, for logging or metrics, without changing the default behaviour. The process still crashes. An `uncaughtException` listener replaces the crash, so you must exit yourself.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark