Error Handling

Error Handling in Node.js: On a large warship, hundreds of things can go wrong at once: a flooded compartment, an electrical fire, a jammed valve, a burst…

The Analogy: The Ship's Damage-Control Central

On a large warship, hundreds of things can go wrong at once: a flooded compartment, an electrical fire, a jammed valve, a burst pipe. The ship does not let each compartment improvise its own response. Instead every compartment is wired to a single Damage-Control Central, a manned station whose only job is to receive incident reports and decide the response. A sailor who discovers a problem does not fight it alone and does not stay silent; they pull the nearest alarm, which sends the report down a dedicated wire straight to DC Central.

DC Central is deliberately the only place that formulates a response. Because every alarm converges there, the crew has exactly one consistent procedure: log the incident, classify its severity, sound the right announcement, and dispatch the right team. There is no scenario where two compartments handle the same fire in two contradictory ways, because no compartment is allowed to handle it at all. Their entire duty on discovering trouble is to route it: pull the alarm and let Central take over.

The wires themselves are the quiet part of the system that makes it work. Each compartment's alarm is physically connected to Central by its own line, tested on every drill. The sailor does not need to know where Central is or who staffs it; they only need to know that pulling the handle puts the report on the wire, and the wire does the delivering. Routing is separated from responding, and that separation is what keeps a chaotic emergency orderly.

Now consider the one failure that defeats the whole design. During a refit, a contractor installs a new pump room but forgets to connect its alarm wire to Central. The pump room looks finished and passes a visual inspection, but when its pump fails at sea, the sailor pulls the alarm and nothing happens at Central: no log, no announcement, no team. The incident is real and in progress, yet Central never hears about it, so the ship keeps steaming as if all is well until the flooding becomes obvious the hard way. This is precisely an unhandled asynchronous error: the failure occurred, but it was never put on the wire to the handler, so the application's central error handler never runs.


Syntax or Core Structure

Express recognizes error-handling middleware by one thing only: the function has FOUR parameters, (err, req, res, next), instead of the usual three. That extra first parameter is the incident report. Express skips these four-argument functions during normal request flow and calls them only when an error has been forwarded, and by convention you register the single central handler LAST, after every route, so it sits at the bottom of the stack like DC Central at the end of every wire. Everything above it is either a normal route that may forward an error or a plain middleware that passes requests along; the four-argument handler alone is the terminus where every forwarded failure finally lands.

The Central Handler

// Registered AFTER all routes. Four args marks it as the error handler.
app.use(function (err, req, res, next) {
  res.status(err.status || 500).json({ error: err.message });
});

Putting an Incident on the Wire

A route forwards an error by calling next(err) with the error as its argument. Any value passed to next other than the string 'route' is treated as an error and skips every remaining normal middleware, jumping straight to the error handler.

app.get('/hazard', function (req, res, next) {
  const problem = new Error('hull breach');
  problem.status = 500;
  next(problem);   // pulls the alarm: report goes to the central handler
});

Synchronous Throws Are Wired for You

Inside a normal route handler, a plain throw is caught by Express automatically and delivered to the error handler; you do not need to call next(err) yourself for synchronous code.

app.get('/sync-throw', function (req, res) {
  throw new Error('valve stuck');   // Express catches this and forwards it
});

Technical Depth: What Is Wired, and What You Must Wire Yourself

The Four-Argument Signature Is Load-Bearing

Express counts parameters at registration time to decide what a function is. Drop the fourth parameter and the same function silently becomes a normal middleware that never runs on errors.

Function shapeExpress treats it asRuns when
(req, res, next)Normal middlewareEvery matching request
(err, req, res, next)Error handlerOnly after next(err) or a sync throw
(req, res)Normal handlerEvery matching request, cannot forward

A Complete Chain: Routes, a 404, and the Handler

The pieces fit in a fixed order: all real routes first, then a three-argument catch-all that converts an unmatched URL into a 404 error, then the four-argument central handler at the very bottom.

const express = require('express');
const app = express();

app.get('/hazard', function (req, res, next) {
  const problem = new Error('hull breach');
  problem.status = 500;
  next(problem);
});

app.get('/safe', function (req, res) {
  res.json({ status: 'all clear' });
});

app.use(function (req, res, next) {
  const miss = new Error('no station for ' + req.method + ' ' + req.path);
  miss.status = 404;
  next(miss);
});

app.use(function (err, req, res, next) {
  res.status(err.status || 500).json({ error: err.message, handledBy: 'damage-control' });
});

A healthy route just answers normally, never touching the error path:

Output:

{"status":"all clear"} [200]

The /hazard route forwards a 500 error with next(problem), and the central handler formats it, tagging who handled it:

Output:

{"error":"hull breach","handledBy":"damage-control"} [500]

An unknown URL falls through every route to the 404 catch-all, which manufactures an error and forwards it to the same central handler:

Output:

{"error":"no station for GET /unknown","handledBy":"damage-control"} [404]

The Wire You Must Connect Yourself: Async Errors

This is the crux. Express automatically forwards synchronous throws, but it does NOT catch a rejected promise or an error thrown inside an async callback. You must connect that wire by catching the error and calling next(err) yourself. The runtime finishes the synchronous part of your handler before the promise settles, so by the time the rejection actually happens Express has already returned from your function and there is no try/catch of its own wrapped around the later async step to intercept it.

Error sourceAuto-forwarded by Express 4?
throw in a sync handlerYes
next(err) callYes, that is the manual wire
rejected promise, no catchNo, escapes as unhandledRejection
throw inside setTimeoutNo, crashes the process

One Handler, Many Status Codes

The central handler does not need to know which route failed; it reads err.status and picks the HTTP code, falling back to 500 when none is set. This lets a single handler distinguish a caller's bad input from a missing record from an outright bug, all through the one expression res.status(err.status || 500).

app.get('/bad-input', function (req, res, next) {
  const e = new Error('missing field: name');
  e.status = 400;
  next(e);
});

app.get('/missing', function (req, res, next) {
  const e = new Error('record 7 not found');
  e.status = 404;
  next(e);
});

app.get('/boom', function (req, res, next) {
  const e = new Error('undefined is not a function');
  next(e);   // no status set: the handler defaults it to 500
});

app.use(function (err, req, res, next) {
  res.status(err.status || 500).json({ error: err.message, code: err.status || 500 });
});

A bad request carries a 400 that the handler echoes straight back to the caller:

Output:

{"error":"missing field: name","code":400} [400]

A lookup that finds nothing forwards a 404, keeping the client contract consistent:

Output:

{"error":"record 7 not found","code":404} [404]

An error created with no status is treated as a server bug and defaults to 500:

Output:

{"error":"undefined is not a function","code":500} [500]

Real World Example: One Handler, Sync and Async Both Wired

This server has two routes that fail in different ways but both reach the same central handler. The first throws synchronously, relying on the wire Express provides for free. The second awaits a rejected promise inside a try/catch and forwards the caught error with next(e), connecting the wire manually.

const express = require('express');
const app = express();

app.get('/sync-throw', function (req, res) {
  throw new Error('valve stuck');
});

app.get('/async-ok', async function (req, res, next) {
  try {
    await Promise.reject(new Error('pump offline'));
  } catch (e) {
    next(e);
  }
});

app.use(function (err, req, res, next) {
  res.status(500).json({ error: err.message, station: 'DC-central' });
});

The synchronous throw is caught by Express and delivered to the handler with no manual forwarding:

Output:

{"error":"valve stuck","station":"DC-central"} [500]

The async route rejects a promise, but because the await sits in a try/catch that calls next(e), the report reaches the same station:

Output:

{"error":"pump offline","station":"DC-central"} [500]

The instructive contrast is with what is NOT shown here, because it cannot be shown as a clean response: if the /async-ok route dropped the try/catch and simply wrote await Promise.reject(...), the rejection would never reach the central handler. In older Express there would be no response at all, the client hanging until timeout, and the process logging an unhandled promise rejection. That is the disconnected alarm wire from the analogy: the failure is real, but it was never put on the wire, so DC Central never hears it. The design flaw to name is that this safety depends entirely on every async route remembering to wrap and forward, a discipline that is easy to forget and invisible when omitted, which is why production apps wrap async handlers in a helper that forwards automatically.


Common Mistakes

  1. Writing an error handler with three parameters. Omitting the err parameter turns the intended handler into an ordinary middleware that never runs on errors, so failures fall through to Express's default handler instead.
  1. Registering the error handler before the routes. Because middleware runs in registration order, an error handler placed above the routes is skipped; it must be the last app.use so every route can forward to it.
  1. Not forwarding async errors. A rejected promise or an error thrown after an await is not caught by Express automatically. Without a try/catch that calls next(err), the request hangs and the process logs an unhandled rejection.
  1. Calling next(err) after already sending a response. If a handler sends a response and then also forwards an error, Express tries to write headers twice, producing the "Cannot set headers after they are sent" crash.
  1. Leaking internal error details to clients. Sending err.stack or a raw database message in the response exposes implementation details and possible secrets. The handler should return a safe message and log the details server-side.
  1. Using throw inside an asynchronous callback. A throw inside a setTimeout or a bare .then runs outside Express's try/catch and crashes the process rather than reaching the handler.
  1. Having more than one competing error handler send a response. Two error handlers that both call res.send cause a double-response error. There should be exactly one terminal error handler, like a single DC Central.
  1. Forgetting the 404 case. With no catch-all for unmatched routes, Express returns its terse default 404 HTML instead of your JSON error shape, giving clients an inconsistent contract.
  1. Swallowing errors in the catch block. A catch (e) {} that neither responds nor calls next(e) hides the failure entirely; the request hangs with no log and no response, the worst of both outcomes.

Best Practices

  • Keep exactly one central error handler, registered last. Route every failure to a single four-argument handler at the bottom of the stack so error formatting lives in one place, mirroring one DC Central for the whole ship.
  • Always forward, never swallow. In every catch block either send a response or call next(err); a catch that does neither is a disconnected alarm wire.
  • Wrap async handlers in a forwarding helper. Use a small asyncHandler(fn) wrapper or a library so that a rejected promise is automatically passed to next, removing the need to remember a try/catch in every route.
  • Attach a status code to errors you create. Set err.status when you build an error so the central handler can choose the right HTTP code instead of defaulting everything to 500.
  • Return safe messages and log the details. Send the client a short, non-sensitive message while logging the stack and context server-side, so debugging stays possible without leaking internals.
  • Add an explicit 404 catch-all before the error handler. Convert unmatched routes into a forwarded 404 error so clients receive the same JSON error shape as every other failure.
  • Distinguish operational from programmer errors. Treat expected failures such as bad input or a missing record as normal 4xx responses, and reserve the 500 path for genuine bugs, so the two are not conflated in logs.
  • Never send two responses for one request. Return immediately after responding and be sure a forwarded error cannot follow a sent response, avoiding the headers-already-sent crash.

Practice Exercises

  1. Build the central handler and forward to it. Write an app with one route that calls next(new Error('boom')) and a single four-argument handler that responds with a 500 and the message. Confirm the handler runs and the route's own code after next does not.
  1. Add a 404 catch-all. Extend the app with a three-argument middleware after the routes that creates a 404 error for any unmatched URL and forwards it to the same handler. Verify a known route still works and an unknown one returns your JSON 404.
  1. Break and fix an async route. Write an async route that awaits a rejected promise WITHOUT a try/catch and observe the request hang, then wrap it so it forwards with next(err). Explain which wire was disconnected in the broken version.
  1. Give errors status codes. Create two routes that forward errors with err.status set to 400 and 404 respectively, and confirm the central handler uses err.status to return the correct code rather than always 500.