Skip to content

Errors as Architecture in Node.js: Safety Nets Against the Crash

Error handling in Node.js is not try/catch cosmetics but a decision about levels, escalation and orderly termination. If you know the four error levels and take graceful shutdown seriously, you build services that die in a controlled way instead of running on in a corrupt state.

≈ 11 min readSoftwareNode.jsBackend

A try/catch catches synchronous exceptions in the currently running stack and rejections of promises that are awaited inside the same block. A later callback, a detached promise and the 'error' event of an EventEmitter, on the other hand, do not reach this block. A try/catch around their mere start call is then just decoration.

This means a Node.js application has at least four levels at which errors arise, and each of them has its own mechanics. If you only know the first one, you have three holes in the net – and you wonder why the process crashes anyway, even though there is “try/catch everywhere.”

Where these nets hang is decided at design time, not in the week before go-live when someone quickly layers some error handling on top. It determines whether a service stops under load and is back fresh within seconds – or whether it keeps working half broken and leaves behind data that nobody can straighten out afterward.

Two axes need to be kept apart here. Callback, promise and EventEmitter describe how an error reaches the code. Operational errors and programmer errors describe whether the concrete state is still manageable. An expected timeout can be answered or retried at the edge of the request. A broken invariant in your own code should escalate to the process boundary so that the service starts fresh after an orderly shutdown. Not every error demands terminating the process; but an unknown program state must not keep running as if it were a normal operational error.

The four levels at which errors arise#

Before we talk about nets, it has to be clear which sources of errors exist in a Node.js application in the first place. At the core there are four, and they differ not in severity but in the mechanism by which the error reaches you:

  • Synchronous: an error is thrown directly in the current call stack. A classic try/catch catches it. If you catch nothing here, the exception is passed up one level – all the way to the top.
  • Error-first callbacks: the old, still ubiquitous Node convention. The error does not come as an exception but as the first argument of the callback function: callback(err, result). No throw, no catch – just a value you have to check actively.
  • Promises and async/await: an error becomes the rejection of the promise. You catch it with .catch() or with try/catch around an await. If it is not caught anywhere, an unhandledRejection occurs.
  • EventEmitter: servers, sockets, streams. The error comes as an 'error' event. And this is where the nastiest trap lurks: if the 'error' listener is missing, the error is not silently swallowed – it is thrown as an exception and takes the process down with it.

Separating these four levels is the first step. The second is understanding that there is a fifth layer above them: the last net, which catches when nobody was responsible on any of the four levels.

Level by level: where the error really arrives#

Let’s go through the levels one by one. Synchronous is simple – everyone knows it:

function parseConfig(raw) {
  try {
    return JSON.parse(raw);
  } catch (err) {
    // synchronous exception, caught right here
    return { ok: false, reason: err.message };
  }
}

The flawed thinking starts as soon as asynchrony comes into play. A try/catch around an error-first callback has no effect, because the callback is called later and in a different stack:

const fs = require('node:fs');

// This try/catch catches NOTHING from the callback below.
try {
  fs.readFile('/etc/config.json', (err, data) => {
    if (err) return handle(err); // the error arrives HERE, as first argument
    process.stdout.write(data);
  });
} catch (err) {
  // never reached for the async error
}

The error sits in the err argument, not in a thrown exception. If you forget the if (err) return ..., the code keeps running with data === undefined – and the actual crash then happens later in a place that has nothing to do with the cause. This is the most common way errors hide in Node.js.

Promises turn this back toward try/catch – but only around await:

async function loadUser(id) {
  try {
    const user = await db.users.findById(id);
    if (!user) throw new Error(`user ${id} not found`);
    return user;
  } catch (err) {
    // rejection AND thrown error both land here
    logger.warn({ err, id }, 'loadUser failed');
    throw err; // re-throw: let the caller decide
  }
}

What matters is the consequence when nobody observes the rejection. Since Node.js 15, the default mode of --unhandled-rejections is throw. An unhandled promise rejection is no longer just a warning but terminates the process. In practice, this means: every asynchronous chain must either be returned to a responsible caller or be handled at a clear boundary at the latest, with .catch or try/catch. Detached promises in timers or callbacks need this boundary explicitly.

The EventEmitter level is the most underestimated. A stream without an 'error' listener crashes the process even though the error would have been entirely manageable:

const fs = require('node:fs');

const stream = fs.createReadStream('/does/not/exist');

// WITHOUT this line, the emitted 'error' is thrown and crashes the process.
stream.on('error', (err) => {
  logger.error({ err }, 'stream failed, handled gracefully');
});

stream.on('data', (chunk) => process.stdout.write(chunk));

This is standard Node semantics: an EventEmitter that emits an 'error' event without a registered listener throws the error. That is why the 'error' handler on servers, sockets and streams is not optional but an architectural must. If you work a lot with process boundaries and streams, you know the pattern from dealing with child_process and scaling – there too, the 'error' event on the child process is the difference between “handled cleanly” and “hard crash.”

The last net – and what it is not there for#

What happens when nobody was responsible on any of the four levels? Then the last net catches it: uncaughtException and unhandledRejection.

flowchart TD
  E["Error occurs"] --> D{"Which level<br/>catches it?"}
  D -->|"try/catch"| H["handle &<br/>continue"]
  D -->|"error-first callback"| H
  D -->|"promise .catch"| H
  D -->|"emitter 'error'"| H
  D -->|"nobody responsible"| ESC["escalates to<br/>the last net"]
  ESC --> LOG["log<br/>uncaughtException /<br/>unhandledRejection"]
  LOG --> GS["start graceful<br/>shutdown"]
  GS --> CLOSE["server.close()"]
  CLOSE --> EXIT["process.exit(1)"]
  EXIT --> SUP["Supervisor<br/>pm2 / systemd / K8s<br/>starts fresh"]

This is the decisive and often misunderstood point. If you register an uncaughtException handler, you override Node’s default behavior. Without a handler, Node writes the stack trace to stderr and terminates the process with exit code 1. As soon as a handler exists, this automatic exit no longer happens. The Node documentation is explicit here: “Adding a handler overrides this default behavior.”

This means: if you register an uncaughtException handler, you have to make sure yourself that the process is terminated. If you do not, it keeps running in an undefined state. And that is exactly the anti-pattern I see most often in real codebases:

// ANTI-PATTERN: swallow and keep running.
process.on('uncaughtException', (err) => {
  logger.error({ err }, 'oops'); // logged, but then... nothing
  // no process.exit — the process stays alive in a corrupt state
});

After an uncaught exception, the application’s state is potentially corrupt: half-completed transactions, leaked file handles, a connection pool in an unclear state. The Node docs explicitly warn against resuming normal operation afterward. uncaughtException and unhandledRejection are a last net for terminating cleanly – not for carrying on.

The right net looks like this: log, then terminate in a controlled way. For the rejection, I deliberately escalate to an exception so that both paths end in the same shutdown:

process.on('unhandledRejection', (reason) => {
  logger.error({ reason }, 'unhandled rejection, escalating');
  // escalate to uncaughtException so we exit through one path
  throw reason;
});

process.on('uncaughtException', (err, origin) => {
  logger.fatal({ err, origin }, 'uncaught exception, shutting down');
  process.exit(1);
});

There is a quieter variant you should know: uncaughtExceptionMonitor. This handler only serves for observing and logging – it does not change the crash behavior. If no uncaughtException handler is registered, the process still crashes, but the monitor has logged beforehand. That is ideal when you want to record the crash without accidentally suppressing it:

// Log the crash without changing the crash behavior.
process.on('uncaughtExceptionMonitor', (err, origin) => {
  logger.fatal({ err, origin }, 'about to crash');
});

Graceful shutdown: die in a controlled way, don’t repair#

The crash via the last net is the hard variant. The normal case in operations is a different one: the supervisor – pm2, systemd or a Kubernetes orchestrator – wants to terminate the process, for example during a deployment or when scaling down. To do so, it sends a SIGTERM. And here the application is responsible for finishing ongoing work cleanly, not for repairing itself.

sequenceDiagram
  participant O as Orchestrator
  participant A as App
  O->>A: SIGTERM
  A->>A: stop accepting new requests
  A->>A: drain in-flight requests
  A->>A: close DB / pools
  A-->>O: exit 0
  O->>O: restart fresh

The sequence is always the same: catch SIGTERM, stop accepting new connections, finish running requests, close resources, then exit. The supervisor then starts a fresh process. What matters is the default you override in doing so: without your own listener, Node exits on SIGTERM with exit code 128 + 15 = 143. As soon as you register a listener, you are responsible for exiting yourself.

const http = require('node:http');

const server = http.createServer(handler);
server.listen(3000);

let isShuttingDown = false;

function shutdown(signal) {
  if (isShuttingDown) return; // guard against double invocation
  isShuttingDown = true;
  logger.info({ signal }, 'graceful shutdown started');

  // stop accepting new connections, finish in-flight ones
  server.close((err) => {
    if (err) {
      logger.error({ err }, 'error during server.close');
      return process.exit(1);
    }
    logger.info('all connections drained, exiting');
    process.exit(0);
  });

  // fallback: never hang forever if a connection refuses to close
  setTimeout(() => {
    logger.error('shutdown timed out, forcing exit');
    process.exit(1);
  }, 10_000).unref();
}

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));

Two details are decisive here. First, the isShuttingDown flag: a container can send SIGTERM and shortly afterward another signal; without a guard, the shutdown runs twice and server.close is called on a server that is already closing. Second, the timeout with .unref(). If a hanging connection causes server.close never to return, the process would otherwise stay up forever – until the orchestrator eventually steps in hard with SIGKILL. The fallback timeout ensures that we exit on our own in a controlled way before that. The .unref() prevents the timer itself from keeping the process alive in case the clean path does finish in time.

This division of labor is the core of the whole architecture: the application is responsible for finishing its ongoing work cleanly and then dying. The supervisor is responsible for restarting – not the application itself. A process that tries to heal itself after a serious error and keep running makes things worse. A process that dies in a controlled way and is restarted fresh is back in a defined state within seconds.

Why this is an architecture decision#

The responsibilities are linked as a chain: the error arises on one of the four levels. Ideally, a responsible handler catches it right there – in the try/catch, in the if (err) check, in the .catch, in the 'error' listener. Only when nobody was responsible does it escalate to the last net, and the last net has exactly one job: log cleanly and terminate in an orderly fashion.

This is not a collection of individual tricks but a consistent decision about where an error is handled and where it only leads to a controlled end. You decide once how the net is strung, and then it holds everywhere – or you do not decide, and then it tears in the place you never looked at.

If you want to dig deeper into the interplay of the event loop, callbacks and promises, you will find the foundation in the Node.js training on event loop architecture. Only once it is clear why a callback runs in a different stack than the try/catch around it does it become understandable why error handling in Node.js is not done with “try/catch everywhere.”

Handle every error as close as possible to the level where it arises. String the last net only for dying cleanly, never for living on. And leave the resurrection to the supervisor. A service that knows how to die is more stable than one that wants to stay alive at any cost.

Further reading#

Revised and translated from German with the help of AI.