Skip to content
jshacks.dev
Patterns

Error Handling Strategies for Large Codebases

Error handling in a large Node.js codebase needs a taxonomy, typed errors, context through cause, one place to log and one to translate. See a working design.

9 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the JavaScript, Node.js, npm, Vite and TypeScript logos.

In a small program, error handling is a try and a catch here and there. In a large codebase with many modules and many developers, the same ad hoc approach produces errors logged five times, messages that leak internals to users, catch blocks that swallow bugs and no way to tell a missing record from a crashed database. Good error handling at scale is a set of agreements: what kinds of errors exist, how they are represented, who adds context, who logs and who decides what the user sees. This post lays out such a design on Node.js 24, with the code and output for each part, and the pitfalls that wear it down over time.

Start with a taxonomy

Two kinds of error need different treatment, and mixing them is the root of most confusion.

Operational errors are problems that happen in a correct program running in a hostile world: the database is unreachable, a user sent bad input, a file does not exist, a remote service timed out. They are expected, so code should handle them: retry, report to the user, fall back.

Programmer errors are bugs: reading a property of undefined, calling a function with the wrong arguments, a broken invariant. Handling them in place is usually wrong, because the program is in a state its author did not anticipate. The right response is to fail loudly, record everything and, for serious ones, let the process restart.

This split, described in the Node.js community's guidance on error handling for years, drives the rest of the design. Operational errors get named types and structured handling. Programmer errors are allowed to propagate to a top-level handler that logs them and returns a generic failure.

Typed errors with stable codes

Strings are a poor way to tell errors apart. Define a small base class, and subclasses for the categories callers need to branch on.

errors.mjsJavaScript
export class AppError extends Error {
  constructor(message, { code, status = 500, cause, expose = false } = {}) {
    super(message, { cause });
    this.name = new.target.name;
    this.code = code;
    this.status = status;
    this.expose = expose;
  }
}

export class NotFoundError extends AppError {
  constructor(what, options) {
    super(`${what} not found`, { code: "NOT_FOUND", status: 404, expose: true, ...options });
  }
}

export class ValidationError extends AppError {
  constructor(message, options) {
    super(message, { code: "VALIDATION", status: 422, expose: true, ...options });
  }
}

const err = new NotFoundError("user 7");
console.log(err.name, err.code, err.status, err.message, err instanceof AppError);
Text
NotFoundError NOT_FOUND 404 user 7 not found true

A few details matter. new.target.name gives each subclass its own name for logs and stack traces. The code is a stable, machine-readable string that you can put in documentation and match in client code, unlike the message, which a developer may reword. And expose marks whether the message is safe to show to an outside caller. A "user 7 not found" message is fine for a client. A database connection string in a message is not, so errors default to expose: false.

Wrap with context, keep the cause

Each layer knows something the layer below does not. The data layer knows the SQL failed. The service layer knows which user was being loaded. Add that context as the error travels up, and keep the original through the cause option, so the root problem and its stack are never lost.

wrap.mjsJavaScript
import { AppError } from "./errors.mjs";

async function loadUser(id, db) {
  try {
    return await db.find(id);
  } catch (err) {
    throw new AppError(`could not load user ${id}`, { code: "DB_ERROR", cause: err });
  }
}

const brokenDb = {
  find: async () => {
    throw new Error("connection refused");
  },
};

try {
  await loadUser(7, brokenDb);
} catch (err) {
  console.log(err.message);
  console.log(err.cause.message);
  console.log(err.status, err.expose);
}
Text
could not load user 7
connection refused
500 false

The outer message says what the program was trying to do, and the cause says why it failed. A logger that prints the error and its chain of causes gives the on-call engineer both. Wrap at layer boundaries and not at every function: a catch that only rethrows the same error adds noise. Also do not wrap errors you cannot add anything to, and never wrap an error you intend to handle completely. If you catch it, handle it.

Handle in one place, translate in one place

Scattered res.status(500).send(...) calls produce inconsistent responses and leak details. Route every failure to a single translation function that turns an error into the response shape.

translate.mjsJavaScript
import { AppError, NotFoundError } from "./errors.mjs";

export function toResponse(err) {
  if (err instanceof AppError && err.expose) {
    return { status: err.status, body: { error: err.code, message: err.message } };
  }
  return { status: 500, body: { error: "INTERNAL", message: "Something went wrong" } };
}

console.log(JSON.stringify(toResponse(new NotFoundError("user 7"))));
console.log(JSON.stringify(toResponse(new AppError("could not load user 7", { code: "DB_ERROR" }))));
console.log(JSON.stringify(toResponse(new TypeError("Cannot read properties of undefined"))));
Text
{"status":404,"body":{"error":"NOT_FOUND","message":"user 7 not found"}}
{"status":500,"body":{"error":"INTERNAL","message":"Something went wrong"}}
{"status":500,"body":{"error":"INTERNAL","message":"Something went wrong"}}

Exposed operational errors tell the client what happened. Everything else, both unexposed application errors and unexpected bugs like the TypeError, becomes a generic 500 with no internals. The real details go to the log, not the response. In an HTTP framework this function sits in the error middleware, and it is the only place that decides what a client sees.

Log once, at the boundary

A common failure in large systems is the same error logged at every layer it passes through: the data layer logs it, the service logs it, the controller logs it, and one incident produces thirty lines that look like thirty problems. The rule is simple: either handle an error or pass it up, and log it only where you handle it, which is usually the boundary at the top.

log-once.mjsJavaScript
function handleRequest(fn, log) {
  return async (...args) => {
    try {
      return await fn(...args);
    } catch (err) {
      log({ level: "error", name: err.name, message: err.message, cause: err.cause?.message });
      throw err;
    }
  };
}

const lines = [];
const handler = handleRequest(
  async () => {
    throw new Error("could not load user 7", { cause: new Error("connection refused") });
  },
  (line) => lines.push(JSON.stringify(line)),
);

await handler().catch(() => {});
console.log(lines);
Text
[
  '{"level":"error","name":"Error","message":"could not load user 7","cause":"connection refused"}'
]

One line carries the whole chain. Add a request id to the log and the line can be joined with the request that caused it. Structured logs, as JSON here, let you search by name or code, which is what makes a taxonomy pay off during an incident.

Results for expected failures

Exceptions work well for failures that should unwind the stack. For expected outcomes that a caller must handle, such as "this input is invalid", returning a result value makes handling explicit and can be easier to follow than a try at every call.

result.mjsJavaScript
const ok = (value) => ({ ok: true, value });
const fail = (error) => ({ ok: false, error });

function parseAge(text) {
  const n = Number(text);
  return Number.isInteger(n) && n >= 0 ? ok(n) : fail(`invalid age: ${text}`);
}

console.log(JSON.stringify(parseAge("30")));
console.log(JSON.stringify(parseAge("abc")));
Text
{"ok":true,"value":30}
{"ok":false,"error":"invalid age: abc"}

The caller cannot forget that failure is possible, since it must look at ok to get the value. Use results where failure is a normal part of the domain, such as parsing and validation, and exceptions where failure is exceptional. Pick one convention per layer and document it, because a codebase that does both everywhere is harder to read than one that does either.

Many failures at once

Parallel work can fail in several ways at once. Promise.all rejects with the first failure and hides the rest, which loses information. Promise.allSettled waits for everything and reports each outcome, and AggregateError is the standard way to package several errors into one.

aggregate.mjsJavaScript
const results = await Promise.allSettled([
  Promise.resolve(1),
  Promise.reject(new Error("task a failed")),
  Promise.reject(new Error("task b failed")),
]);

const failures = results.filter((r) => r.status === "rejected").map((r) => r.reason);
console.log(failures.map((e) => e.message));

if (failures.length > 0) {
  const error = new AggregateError(failures, `${failures.length} tasks failed`);
  console.log(error.message, error.errors.length);
}
Text
[ 'task a failed', 'task b failed' ]
2 tasks failed 2

Batch jobs and fan-out requests benefit from this: report every failure, not only the first, so an operator can fix all of them in one pass.

The last line of defense

Some errors escape every handler. A rejected promise that nobody awaited, or an exception thrown from a timer callback, reaches the process level. In Node.js, an unhandled rejection terminates the process by default, and an uncaught exception does too. That default is right: after an unexpected error, the program's state is unreliable. Register handlers only to log and shut down cleanly.

last-resort.mjsJavaScript
process.on("uncaughtException", (err) => {
  console.error("fatal:", err.message);
  process.exit(1);
});

process.on("unhandledRejection", (reason) => {
  throw reason;
});

The second handler rethrows the rejection reason so it reaches the first one, giving a single path to shutdown. Run under a process manager or an orchestrator that restarts the service, and a crash on a bug becomes a brief blip and not a corrupted state. Do not use these handlers to keep running, since that is how a bug quietly poisons data.

Rules that keep it working over years

  • Throw errors, never strings or plain objects. Only Error instances carry a stack.

  • Name every expected failure. If callers need to branch on it, give it a class or a code.

  • Do not catch what you cannot handle. A catch that logs and continues turns a failure into silent wrong behavior.

  • Never expose internals. The translation function is the only door to the client, and it defaults to hiding.

  • **Check err instanceof or err.code, not message text.** Messages change.

  • Make failures testable. Each documented error should have a test that triggers it.

Testing the policy

errors.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";
import { NotFoundError, AppError } from "./errors.mjs";
import { toResponse } from "./translate.mjs";

test("exposed errors become precise responses", () => {
  assert.deepEqual(toResponse(new NotFoundError("post 3")), {
    status: 404,
    body: { error: "NOT_FOUND", message: "post 3 not found" },
  });
});

test("unexposed errors never leak their message", () => {
  const response = toResponse(new AppError("password for admin is wrong", { code: "X" }));
  assert.equal(response.status, 500);
  assert.ok(!JSON.stringify(response).includes("password"));
});
Text
✔ exposed errors become precise responses (0.9ms)
✔ unexposed errors never leak their message (0.3ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

The second test is the one that matters for security: it proves that an internal message does not reach the client.

When not to build all this

A script, a prototype or a service with three endpoints does not need a taxonomy and a translation layer. Start with the discipline: throw Error objects, keep causes, and log at one place. Add typed errors when a second caller needs to tell two failures apart, and add the translation layer when the second route needs the same response shape.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.