Error Handling in Node That Does Not Lose the Error
JavaScript & Node.js

Error Handling in Node That Does Not Lose the Error

2 October 20266 min read1018 words
Tags#nodejs#error-handling#async#debugging

Something failed in production. The log shows a line that says Error and nothing else, or worse, nothing at all and a process that quietly restarted. Error handling in Node is not complicated, but it has two traps that catch nearly everyone: asynchronous work escapes try/catch, and a caught error is easy to destroy on the way up. This post covers where errors actually go and how to keep them intact.

Where an error ends up

A thrown error travels up the call stack until something catches it. That works exactly as you expect for synchronous code. It stops working the moment a callback or a promise is involved, because by the time the callback runs, the stack that contained your try is gone.

// Does NOT catch anything
try {
  setTimeout(() => { throw new Error('boom'); }, 10);
} catch (err) {
  console.error('never reached');
}

The same applies to a rejected promise you forgot to await. The error exists, it just has nowhere to go, and it surfaces later as an unhandled rejection rather than at the line you were watching.

async/await, and the missing await

With async/await, try/catch works again, as long as the failing call is actually awaited inside the block.

try {
  const user = await getUser(id);       // caught
  saveAudit(user);                      // NOT caught: no await
} catch (err) {
  log.error({ err }, 'could not load user');
}

That second line is the single most common error-handling bug in Node code. The call returns a promise, the function moves on, and when the promise rejects there is no longer a try block anywhere near it. Either await it, or handle it explicitly with a .catch() if you deliberately want it to run in the background.

When you fire several things at once, remember that Promise.all rejects on the first failure and leaves the others running. If you need all the results, successes and failures both, use Promise.allSettled and inspect each outcome.

Unhandled rejections and uncaught exceptions

Node emits unhandledRejection when a promise rejects with nobody listening, and uncaughtException when a throw reaches the top. Modern Node terminates the process on an unhandled rejection by default, and that default is the right one.

The temptation is to install a handler that logs the error and keeps running. Resist it for anything but logging. After an uncaught exception the process is in a state nobody reasoned about: a half-written file, a transaction never committed, a connection pool with a leaked client. Log with as much context as you can, then let the process exit and let your supervisor, whether that is systemd, Docker, Kubernetes or your platform, start a clean one.

process.on('unhandledRejection', (err) => {
  log.fatal({ err }, 'unhandled rejection');
  process.exit(1);   // let the supervisor restart us
});

What you do want before exiting is a graceful shutdown path: stop accepting new requests, give in-flight ones a few seconds, close the database pool. That turns a crash from a spike of failed requests into a blip.

Catch at a boundary, not everywhere

A try/catch around every call produces code that is hard to read and logs that repeat the same failure five times. Catch where you can actually do something, which in most services means one of three places:

  • The request handler. Turn the error into a status code and a response the client can act on. Most frameworks have one error middleware for this; use it instead of catching in each route.
  • The job runner. Decide whether the job retries, goes to a dead-letter queue, or fails permanently.
  • A place with a fallback. If a cache read fails and you can go to the database instead, catch there, and log it at a lower level than an outage.

Everywhere else, let it travel. If you do catch in the middle to add context, rethrow afterwards.

Keep the cause

A caught error loses its value when you replace it with a message. These three lines destroy information in order of severity: throwing a string instead of an Error, logging err.message without the stack, and catching an error to throw a brand new one with no link to the original.

The fix for the third is built into the language:

try {
  await db.insert(row);
} catch (err) {
  throw new Error('could not save invoice', { cause: err });
}

The cause option keeps the original error, with its stack, reachable from the new one, so the log shows both the business-level description and the driver error underneath. For errors you want to react to differently, a small class per category works better than checking message text:

class NotFound extends Error {}
class ValidationFailed extends Error {}

Now the boundary can map a NotFound to a 404 and a ValidationFailed to a 400 without parsing strings. Node errors from the runtime and the drivers already carry a code property, such as ENOENT or a database error code; prefer that over matching on the message, which changes between versions.

What the client sees, and what you keep

Internal messages do not belong in an API response. Return a short, stable message plus an identifier, and log the full error with that same identifier. When a user reports a problem, the identifier takes you straight to the entry.

const id = crypto.randomUUID();
log.error({ err, id, route: req.path }, 'request failed');
res.status(500).json({ error: 'Something went wrong', id });

Log errors as structured objects rather than interpolated strings. A logger that receives the error object records the stack, the cause chain and the code; a template string records one line of text.

A short checklist

  • Every promise is awaited, or has an explicit catch.
  • unhandledRejection and uncaughtException log and exit, with a graceful shutdown.
  • Errors are caught at boundaries; anything caught in between is rethrown with cause.
  • Only Error objects are thrown, and categories are classes or codes, not message text.
  • The response carries an identifier that appears in the log line.

None of this is glamorous, and all of it is the difference between an incident you can read in five minutes and one you reconstruct from guesswork.

Comments

No comments yet. Be the first to share your thoughts.

Node.js Error Handling: Async, Rejections, Boundaries