Loading

T9 APIs · Lesson 6

Error handling

An API is judged by how it fails. Follow every kind of error from where it happens to what the client sees, give each one the same shape with a status, a code, a message and details, write the handlers in order, and deal with the failures that are not errors at all: a route that never answers, and a throw outside the request's path.

  • say where each kind of error lands: a throw, a rejected promise, next(err), and an error inside a middleware, a router or a parser
  • read what Express's own handler answers, and why a real API writes its own
  • give every error one shape, with a status, a code, a message and details, through a class of your own
  • answer each parser error with the right status, and a validation error with every problem at once
  • write several error handlers in order, pass an error on, and deal with an error after the headers have gone
  • handle the failures outside a request: a route that never answers, a throw outside the request's path, and a promise nobody waited for
About 70 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-15); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-15); Express, from npm (the kit compares every Express block with it, in its sandbox; the page runs the small Express of plan 25) 5.3.0 (2026-11-15)Play this lesson's games

The back cover

A good courier office is judged by its returned parcels as much as by its deliveries. Every parcel that cannot be delivered comes back with a slip. Every slip is filled in the same way: what went wrong, a code for the office's records, and what the sender can do about it.

These pages follow every kind of error from where it happens to what the client sees. They give each error one shape, write the handler that answers them all, fold the parsers' errors into that shape, and chain several handlers in order. Last, they ring a bell for the failures that throw nothing at all.

Before you start

The story: A ledger of smashed parcels

A courier drops a crate at the gate and it bursts. The clerk at the far end of the belt sends the sender a sheet covered in the yard's own handwriting: every bench the crate passed, the time of day, the clerk's name. The sender learns nothing, except that something broke.

Another parcel, packed wrongly, comes back with one word on it: no. A third sits on the belt for an hour, because its bench never answered, and the courier waits beside it.

Yardmaster Waybill lays the three slips side by side. "A yard is judged by how it fails," she says. "Every failure gets one kind of slip, in words the sender can act on, and nothing the sender has no business reading. And no parcel waits for ever. Learn to fail well."

Every lesson so far ended with an error handler: a function of four parameters, last in the line, that turns a throw into a JSON answer. That was the beginning of error handling, not the whole of it.

This lesson follows every kind of failure from where it happens to what the client sees. It covers errors in routes, in middleware, in parsers and after an await, and the shape of a good error answer. Then come the handlers in order, and the failures that are not errors at all, such as a route that never answers.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
throw and try.throw new Error("...")Every error starts here.
Error objects.err.message, err.stackWhat to show and what to hide.
Classes and extends.class HttpError extends ErrorOne kind of error for the API.
The error handler.(err, req, res, next)Several of them, in order.
next(err).next(new Error(...))Passing an error on by hand.
Promises and async.await, a rejected promiseErrors after an await.
Status codes.400, 404, 500413, 415, 422 and 503 join them.
express.json.entity.parse.failedEvery error a parser can raise.
Checking a body.every problem at once (lesson 02)Validation errors with details.
Timers and events.setTimeout, res.on("finish")A bell for a route that never answers.

By the end of this lesson you will be able to:

  • say where each kind of error lands: a throw, a rejected promise, next(err), and an error inside a middleware, a router or a parser;
  • read what Express's own handler answers, and why a real API writes its own;
  • give every error one shape, with a status, a code, a message and details, through a class of your own;
  • answer each parser error with the right status, and a validation error with every problem at once;
  • write several error handlers in order, pass an error on, and deal with an error after the headers have gone;
  • handle the failures outside a request: a route that never answers, a throw outside the request's path, and a promise nobody waited for.

How to follow this lesson

Every block is an Express app and its own client, as in lessons 03 to 05. It runs on the page in the small Node with its small Express, and it has also been run with the real Express 5.3.0 in real Node 22, where it prints the same.

Some blocks let an error reach Express's own handler on purpose, to show its page. Those run node with 2>/dev/null, because Express also writes the error's stack to the terminal's error stream, in an order that races with the client's lines.

In one line

An API fails well when every failure, wherever it starts, reaches one handler and leaves as one kind of answer: a status, a code, a message the client can act on, and nothing it has no business reading.

Where every error lands

At a glance

An API is judged by how it fails. Every error starts somewhere and ends as an answer that a client sees.

An error can start in a route, a middleware, a router, an async handler or a call to next(err). Wherever it starts, it travels down the line to the next error handler. When there is none, Express's own default handler answers, in HTML. In development it shows the message and the stack. In production it shows only the name of the status, such as Internal Server Error.

Take a guess: Can an error page help an attacker?

Something goes wrong inside a route: a throw, a promise that rejects, a call to next with an error. Where does it go? Express has one rule: every error travels down the line to the next error handler, the function with four parameters. When your app has none, Express's own handler, the default handler, takes it.

You met the default handler's page in lesson 04. Here it is twice, for the same error, run in two settings:

app.js

const express = require("express");
const app = express();
app.get("/boom", (req, res) => { throw new Error("the boiler burst"); });
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/boom");
  const body = await r.text();
  console.log(app.get("env"), r.status, r.headers.get("content-type"));
  console.log(body.match(/<pre>(.*?)(?:<br>|<\/pre>)/)[1]);
  server.close();
});

Terminal: node app.js 2>/dev/null; NODE_ENV=production node app.js 2>/dev/null

development 500 text/html; charset=utf-8
Error: the boiler burst
production 500 text/html; charset=utf-8
Internal Server Error

The first run is the ordinary one. app.get("env") answers development, and the page carried the error's own words, and below them, hidden here, its whole stack: every file and line the error passed through.

The second run set the environment variable NODE_ENV to production, which app.get("env") reads. Then the page said only Internal Server Error. The stack, the file names and the message stayed on the server, because in production they are for the owner's eyes.

The default handler also reads an error's status. An error with err.status set to 404 answers 404, with its message in development and the status's name in production:

app.js

const express = require("express");
const app = express();
app.get("/gauges/:name", (req, res) => {
  const e = new Error(`no gauge called ${req.params.name}`);
  e.status = 404;
  throw e;
});
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges/fan");
  const body = await r.text();
  console.log(r.status, body.match(/<pre>(.*?)(?:<br>|<\/pre>)/)[1]);
  server.close();
});

Terminal: node app.js 2>/dev/null; NODE_ENV=production node app.js 2>/dev/null

404 Error: no gauge called fan
404 Not Found

So the default handler is safe in production and helpful in development, and it always answers in HTML. A JSON API wants JSON, with a message the client can act on. That is why every lesson ends its app with an error handler of its own, and why this lesson is about writing a good one.

SettingThe default handler's page showsStatus
development (the default)the error's message and its stackerr.status, or 500
production (NODE_ENV=production)the status's name only, such as Not Founderr.status, or 500

From anywhere in the line

An error handler receives errors from every function above it: a middleware, a route, a router mounted at a path. And next can carry anything, not only an Error. Here four errors start in four places, and one handler reports what it got:

app.js

const express = require("express");
const app = express();
app.use((req, res, next) => {
  if (req.path === "/mw") throw new Error("broke in a middleware");
  next();
});
app.get("/str", (req, res, next) => next("a plain string"));
app.get("/num", (req, res, next) => next(42));
const sub = express.Router();
sub.get("/x", (req, res) => { throw new Error("broke inside a router"); });
app.use("/sub", sub);
app.use((err, req, res, next) => res.status(500).json({ kind: typeof err, message: err instanceof Error ? err.message : String(err) }));
const server = app.listen(3000, async () => {
  for (const p of ["/mw", "/str", "/num", "/sub/x"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

/mw 500 {"kind":"object","message":"broke in a middleware"}
/str 500 {"kind":"string","message":"a plain string"}
/num 500 {"kind":"number","message":"42"}
/sub/x 500 {"kind":"object","message":"broke inside a router"}

The middleware's throw and the router's throw arrived as Error objects. The string arrived as a string, and 42 as a number. Express passes along whatever next was given, as long as it is not the words route or router, which have their own meaning from lesson 03.

Throw Error objects, and only those. An error that is a string has no stack, no status and no place to hang a code, and a handler that reads err.message gets undefined.

Errors that happen later

A route often does its work after an await, or inside a callback. Express 5 catches a rejected promise from an async handler, as lesson 04 showed. A callback is different: Express cannot see inside it, so the callback must hand the error to next itself:

app.js

const express = require("express");
const app = express();
app.get("/a", async (req, res) => {
  await new Promise((resolve) => setTimeout(resolve, 10));
  throw new Error("after an await");
});
app.get("/b", (req, res, next) => {
  setTimeout(() => next(new Error("from a callback, passed on properly")), 10);
});
app.use((err, req, res, next) => res.status(500).json({ error: err.message }));
const server = app.listen(3000, async () => {
  for (const p of ["/a", "/b"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

/a 500 {"error":"after an await"}
/b 500 {"error":"from a callback, passed on properly"}

Both reached the handler. The async route's throw became a rejected promise, which Express 5 turned into next(err). The callback called next(err) by hand. A callback that throws instead of calling next(err) is a different story, told in the last section: nobody is there to catch it.

Where the error startsHow it reaches the handler
a throw in a route or middlewareExpress catches it and calls next(err)
a throw after an await, in an async handlerthe promise rejects; Express 5 calls next(err)
next(err) anywhere, a callback includedit goes straight to the next error handler
a throw inside a callback, such as a timer'sit does not reach the handler; the process crashes

Worked example 1

Follow two errors that start deep inside helper functions, not in the route itself: a missing gauge that a helper refuses, and a crash inside another helper.

What we have: two helpers, latest and average, and two routes that call them

What we need: 200 for the boiler, and for the fan, a refusal from one helper and a TypeError from the other, both caught by the handler

The plan: let the helpers throw as they like; one error handler at the end prints each error's class and message, and answers 500

app.js

const express = require("express");
const app = express();
const readings = { boiler: [95, 96] };
function latest(name) {
  if (!readings[name]) throw new Error(`no readings for ${name}`);
  return readings[name].at(-1);
}
function average(name) {
  const list = readings[name];
  return list.reduce((a, b) => a + b, 0) / list.length;
}
app.get("/latest/:name", (req, res) => res.json({ latest: latest(req.params.name) }));
app.get("/average/:name", (req, res) => res.json({ average: average(req.params.name) }));
app.use((err, req, res, next) => {
  console.log("caught:", err.constructor.name, "|", err.message);
  res.status(500).json({ error: "something broke on our side" });
});
const server = app.listen(3000, async () => {
  for (const p of ["/latest/boiler", "/latest/fan", "/average/fan"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

/latest/boiler 200 {"latest":96}
caught: Error | no readings for fan
/latest/fan 500 {"error":"something broke on our side"}
caught: TypeError | Cannot read properties of undefined (reading 'reduce')
/average/fan 500 {"error":"something broke on our side"}
  1. latest threw on purpose, with a message of its own, two calls below the route. The throw climbed out of the helper, out of the route, and Express caught it.
  2. average did not check, so reduce was called on undefined, and JavaScript threw a TypeError. That climbed the same way and landed in the same handler.
  3. The handler printed the class and the message on the server and sent the client a plain sentence: the inside of a crash is not for the client.

The handler caught Error, no readings for fan and TypeError, Cannot read properties of undefined, and answered 500 to both.

Check: Both errors started two calls below the route, and both reached the one handler at the end.

Another way: give the first error a status of 404 before throwing it, as lesson 04 did, so that the handler can tell a client's mistake from a crash. The next section makes that a habit.

A path that fails: wrapping every helper call in try and catch inside the route, and sending a 500 from each. The same lines would be written in every route; one handler at the end does it once.

When you are stuck: An error never reaches my handler

Does it start in a callback? A throw inside a timer or a stream's listener does not reach Express; call next(err) there instead.

Is the handler below the place where the error starts, with four parameters? Errors travel down, never up.

Is the page HTML, with a stack? Then no handler of yours received it: Express's own did.

Your turn

A route runs under NODE_ENV=production and throws new Error("the boiler burst"). What does the default handler's page say?Tap to reveal
  1. In production, the words of the error stay on the server.

Internal Server Error, the name of status 500, and nothing more.

A route calls next("jammed"). What is err in the error handler, and what does err.message give?Tap to reveal
  1. Express passes along what next was given.

err is the string jammed, and err.message is undefined: throw Error objects instead.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/", async (req, res) => {
  await Promise.resolve();
  throw new Error("late");
});
app.use((err, req, res, next) => res.status(500).send("caught " + err.message));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/");
  console.log(r.status, await r.text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
500 caught late
  1. The throw after an await rejects the handler's promise.
  2. Express 5 passes a rejected promise to the error handler.

It prints 500 caught late.

Did you know?

Errors that help an attacker

Error pages can help an attacker. OWASP's cheat sheet on error handling says that an attack begins with reconnaissance, a search for technical details such as the server, frameworks and libraries, and that unhandled errors can help in this first phase. Express's security guide calls it fingerprinting, and says that making it harder improves an app's overall security.

Why it fits here: It answers this topic's question: a stack trace tells an attacker what a server runs, so production hides it.

Sources: OWASP Cheat Sheet Series: Error Handling; Express: Security best practices

Production runs faster too

One setting changes more than error pages. Express's performance guide says that setting NODE_ENV to production makes Express cache view templates and the CSS built from CSS extensions, and generate less verbose error messages. It adds that tests indicate this alone can improve an app's performance by a factor of three.

Why it fits here: It adds to this topic's production mode: NODE_ENV=production hides stacks and, by Express's tests, can make an app three times faster.

Source: Express: Performance best practices

In one line

Every error, from a route, a middleware, a router, an async handler or a next(err), travels down to the next error handler. With none, Express's default handler answers in HTML: the message and stack in development, the status's name alone in production.

One shape for every error

At a glance

A client reads errors with code, so every error should look the same.

A class that extends Error gives every error one shape: a status for HTTP, a code in capitals for programs, such as GAUGE_NOT_FOUND, a message for people, and details when they help. One handler at the end answers every known error with its own fields. A crash gets 500 and one plain sentence, never the server's insides. Even the 404 for an unknown path becomes an error of this shape.

Take a guess: Can an API make up a status code of its own?

Lesson 04 gave an error a status before throwing it, with err.status = 404. That works, but it is loose: every route sets the fields it remembers, and the handler must guess what it was given. A real API decides once what an error looks like, and keeps to it.

The usual way is a class of your own that extends Error. It carries a status, a short code that programs can read, a message that people can read, and, when there is more to say, details:

app.js

const express = require("express");
const app = express();
class HttpError extends Error {
  constructor(status, code, message, details) {
    super(message);
    this.status = status;
    this.code = code;
    this.details = details;
  }
}
const gauges = { boiler: 95 };
app.get("/gauges/:name", (req, res) => {
  if (!Object.hasOwn(gauges, req.params.name)) throw new HttpError(404, "GAUGE_NOT_FOUND", `no gauge called ${req.params.name}`);
  res.json({ value: gauges[req.params.name] });
});
app.use((err, req, res, next) => {
  if (err instanceof HttpError) return res.status(err.status).json({ status: err.status, code: err.code, message: err.message });
  res.status(500).json({ status: 500, code: "INTERNAL", message: "something broke on our side" });
});
const server = app.listen(3000, async () => {
  for (const name of ["boiler", "fan"]) {
    const r = await fetch("http://localhost:3000/gauges/" + name);
    console.log(r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

200 {"value":95}
404 {"status":404,"code":"GAUGE_NOT_FOUND","message":"no gauge called fan"}

HttpError extends Error, so a throw of it climbs out of a route like any error, and err instanceof HttpError tells the handler that this one was made on purpose, with a status the client should see. Anything else is a crash, which gets 500 and a plain sentence.

The code is the part most APIs forget. A message may change its wording; a code such as GAUGE_NOT_FOUND is a promise to the client's program, which can branch on it without reading English.

FieldFor whomExample
statusHTTP, and the client's first check404
codethe client's program: stable, in capitalsGAUGE_NOT_FOUND
messagethe person reading the answerno gauge called fan
detailsthe client's program, when one message is not enougha list of every problem with a body

The handler that answers everything

With one class, one handler at the end of the line can answer every failure the same way. A known error gets its own status, code and message; a crash gets 500 and nothing from the inside; and the API's 404 is now an error too:

app.js

const express = require("express");
const app = express();
class HttpError extends Error {
  constructor(status, code, message, details) {
    super(message);
    this.status = status;
    this.code = code;
    this.details = details;
  }
}
const gauges = { boiler: 95 };
app.use(express.json());
app.get("/gauges/:name", (req, res) => {
  if (!Object.hasOwn(gauges, req.params.name)) throw new HttpError(404, "GAUGE_NOT_FOUND", `no gauge called ${req.params.name}`);
  res.json({ value: gauges[req.params.name] });
});
app.post("/readings", (req, res) => {
  const problems = [];
  if (typeof req.body.gauge !== "string") problems.push("gauge must be a string");
  if (typeof req.body.value !== "number") problems.push("value must be a number");
  if (problems.length) throw new HttpError(400, "INVALID_BODY", "the body has problems", problems);
  res.status(201).json({ saved: req.body });
});
app.get("/crash", (req, res) => { throw new Error("a broken gear"); });
app.use((req, res, next) => next(new HttpError(404, "NO_ROUTE", `no route for ${req.method} ${req.originalUrl}`)));
app.use((err, req, res, next) => {
  const known = err instanceof HttpError;
  if (!known) console.log("logged on the server:", err.message);
  const status = known ? err.status : 500;
  res.status(status).json({ status, code: known ? err.code : "INTERNAL", message: known ? err.message : "something broke on our side", ...(err.details ? { details: err.details } : {}) });
});
const server = app.listen(3000, async () => {
  const url = "http://localhost:3000";
  const answers = [
    await fetch(url + "/gauges/fan"),
    await fetch(url + "/readings", { method: "POST", headers: { "Content-Type": "application/json" }, body: '{"value":"hot"}' }),
    await fetch(url + "/crash"),
    await fetch(url + "/nowhere"),
    await fetch(url + "/readings", { method: "POST", headers: { "Content-Type": "application/json" }, body: '{"gauge":"boiler","value":96}' }),
  ];
  for (const r of answers) console.log(r.status, await r.text());
  server.close();
});

Terminal: node app.js

logged on the server: a broken gear
404 {"status":404,"code":"GAUGE_NOT_FOUND","message":"no gauge called fan"}
400 {"status":400,"code":"INVALID_BODY","message":"the body has problems","details":["gauge must be a string","value must be a number"]}
500 {"status":500,"code":"INTERNAL","message":"something broke on our side"}
404 {"status":404,"code":"NO_ROUTE","message":"no route for GET /nowhere"}
201 {"saved":{"gauge":"boiler","value":96}}

Read the five answers against the five requests. The missing gauge and the unknown address both got 404, with different codes, because they are different mistakes. The bad body got 400 with its details. The crash got 500 and a plain sentence, and its real message went to the server's log, printed first because the server printed it while handling the request.

The 404 middleware no longer answers by itself. It makes an HttpError and passes it to next, so that the error handler stays the only place that writes an error answer. One place, one shape.

Express's own fields

Express's default handler reads err.status or err.statusCode for the status, and err.expose, when set, says whether the message may be shown. The http-errors package, which Express itself uses for its parsers' errors, builds errors with those fields: createError(404, "no gauge"). A class of your own can set the same names, so that both handlers understand it.

The default handler also copies err.headers onto the answer, so that an error can carry a header such as Retry-After:

app.js

const express = require("express");
const app = express();
app.get("/", (req, res, next) => {
  const e = new Error("the stoker is away");
  e.status = 503;
  e.headers = { "Retry-After": "30" };
  next(e);
});
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/");
  console.log(r.status, r.headers.get("retry-after"));
  server.close();
});

Terminal: node app.js 2>/dev/null

503 30

503 Service Unavailable with Retry-After: 30 tells a well-behaved client to try again in thirty seconds. In your own handler, if (err.headers) res.set(err.headers) does the same.

Worked example 2

Write a client that acts on the code, not the words: a locked gauge asks for the key, a missing gauge is reported, and anything else is shown as a failure.

What we have: a gauges route that throws GAUGE_NOT_FOUND or GAUGE_LOCKED, and a client function read that reads the answer's JSON

What we need: three lines: no such gauge, locked, then the value once the key is sent

The plan: throw HttpError with a code for each case; in the client, check r.ok first, then branch on body.code

app.js

const express = require("express");
const app = express();
class HttpError extends Error {
  constructor(status, code, message) { super(message); this.status = status; this.code = code; }
}
const gauges = { boiler: { value: 95, locked: true } };
app.get("/gauges/:name", (req, res) => {
  const gauge = gauges[req.params.name];
  if (!gauge) throw new HttpError(404, "GAUGE_NOT_FOUND", `no gauge called ${req.params.name}`);
  if (gauge.locked && req.get("x-key") !== "brass") throw new HttpError(403, "GAUGE_LOCKED", "this gauge needs the brass key");
  res.json({ value: gauge.value });
});
app.use((err, req, res, next) => res.status(err.status ?? 500).json({ code: err.code ?? "INTERNAL", message: err.status ? err.message : "something broke on our side" }));
async function read(name, headers = {}) {
  const r = await fetch("http://localhost:3000/gauges/" + name, { headers });
  const body = await r.json();
  if (r.ok) return `${name}: ${body.value}`;
  if (body.code === "GAUGE_LOCKED") return `${name}: locked, send the key`;
  if (body.code === "GAUGE_NOT_FOUND") return `${name}: no such gauge`;
  return `${name}: failed (${body.code})`;
}
const server = app.listen(3000, async () => {
  console.log(await read("fan"));
  console.log(await read("boiler"));
  console.log(await read("boiler", { "X-Key": "brass" }));
  server.close();
});

Terminal: node app.js

fan: no such gauge
boiler: locked, send the key
boiler: 95
  1. The client never reads the message. It reads code, which will not change when the wording does.
  2. r.ok is true for any status from 200 to 299, so the first check separates success from every failure.
  3. The last line is the else: a code the client does not know is still reported, with the code, so that someone can look it up.

no such gauge, locked, send the key, then boiler: 95.

Check: Each answer's code chose one line of the client's; the messages were never compared.

Another way: put the codes in one shared file that both the server and the client import, so that a misspelt code fails at once instead of falling through to the else.

A path that fails: branching on the message: if (body.message === "this gauge needs the brass key"). The first rewording on the server breaks every client.

When you are stuck: The handler cannot tell my errors from crashes

Does every error you throw on purpose come from your class? One stray new Error with a status set by hand is still caught, but err instanceof HttpError is false for it.

Is the status on the error, not only in the message? The handler reads err.status.

Is the code stable? If a client sees a new code for an old mistake, you renamed it; codes are a promise.

Your turn

Why does a good error answer carry a code as well as a message?Tap to reveal
  1. Think about who reads each one.

The message is for people and may be reworded; the code is for programs and never changes.

Which status should the handler use for an error that is not an HttpError, and what should its message say?Tap to reveal
  1. It was not thrown on purpose.

500, with a plain sentence; the real message goes to the server's log only.

cat > app.js <<'END'
const express = require("express");
const app = express();
class HttpError extends Error { constructor(status, code, message) { super(message); this.status = status; this.code = code; } }
app.get("/", (req, res) => { throw new HttpError(409, "ALREADY_THERE", "a reading for this minute exists"); });
app.use((err, req, res, next) => res.status(err.status ?? 500).json({ code: err.code }));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/");
  console.log(r.status, await r.text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
409 {"code":"ALREADY_THERE"}
  1. The class carries the status and the code.
  2. The handler reads both from the error.

It prints 409 {"code":"ALREADY_THERE"}.

Did you know?

No made-up status codes

An API cannot invent a status code of its own. IANA keeps the registry of HTTP status codes, and RFC 9110 says that new values require IETF Review, so a new code needs the agreement of the IETF. That is why an API puts its own detail in a code inside the body, such as GAUGE_NOT_FOUND, and keeps to the standard statuses.

Why it fits here: It answers this topic's question: new HTTP statuses need IETF Review, so an API's own detail goes in the body's code.

Sources: RFC 9110: HTTP Semantics; IANA: HTTP Status Codes

Problem Details, since 2016

The shape of this lesson's answers has a standard older than it seems. RFC 7807, Problem Details for HTTP APIs, came in March 2016, and RFC 9457 replaced it in July 2023. A body in that shape is sent with the media type application/problem+json, so a client can tell the shape from the label alone, before it reads a word.

Why it fits here: It dates this topic's shape: Problem Details has been a standard since 2016, labelled application/problem+json.

Sources: RFC 7807: Problem Details for HTTP APIs; RFC 9457: Problem Details for HTTP APIs

In one line

Give every error one shape through a class that extends Error, with a status, a code in capitals for programs, a message for people and details when needed. One handler at the end answers known errors with their own fields, crashes with 500 and a plain sentence, and the 404 is an error too.

Errors from the parsers, and validation

At a glance

Some errors come from Express's own body readers, before any route runs.

A parser's error carries err.type, such as entity.parse.failed for broken JSON or entity.too.large for a body over the limit, and err.status, 400, 413 or 415. It also carries expose, which says whether its message is safe to show. Translate each type into your own code and message, replace the wording of JSON.parse, and set a limit that fits the API. Validation problems are answered all at once, in the same shape.

Take a guess: Is a body's size the only limit a parser keeps?

Before a route sees a body, express.json has read it, and four things can go wrong on the way. The body may not be JSON. It may be bigger than the parser allows. It may be written in a character set the parser cannot read, or squeezed with a content encoding it cannot undo.

Each failure becomes an error with a type, a status and a message, passed to next(err) before the route runs. One handler prints all four, with a limit of twenty bytes to make the second one easy to reach:

app.js

const express = require("express");
const app = express();
app.use(express.json({ limit: "20b" }));
app.post("/r", (req, res) => res.sendStatus(201));
app.use((err, req, res, next) => {
  const message = err.type === "entity.parse.failed" ? "the body is not valid JSON" : err.message;
  res.status(err.status).json({ status: err.status, type: err.type, message });
});
const server = app.listen(3000, async () => {
  const send = (body, headers) => fetch("http://localhost:3000/r", { method: "POST", headers: { "Content-Type": "application/json", ...headers }, body });
  const answers = [
    await send("{bad", {}),
    await send('{"value":95,"note":"too long"}', {}),
    await send('{"a":1}', { "Content-Type": "application/json; charset=foo" }),
    await send('{"a":1}', { "Content-Encoding": "foo" }),
    await send('{"a":1}', {}),
  ];
  for (const r of answers) console.log(r.status, await r.text());
  server.close();
});

Terminal: node app.js

400 {"status":400,"type":"entity.parse.failed","message":"the body is not valid JSON"}
413 {"status":413,"type":"entity.too.large","message":"request entity too large"}
415 {"status":415,"type":"charset.unsupported","message":"unsupported charset \"FOO\""}
415 {"status":415,"type":"encoding.unsupported","message":"unsupported content encoding \"foo\""}
201 Created

Look at the fields on each error. err.type names what went wrong, in the parser's own words. err.status is the status that fits: 400 for a client's broken JSON, 413 Content Too Large for a body over the limit, 415 Unsupported Media Type for the two the parser cannot read.

The handler replaced one message. A parse error's message comes from JavaScript's own JSON.parse, and its wording changes from one version to the next, so the handler gave its own instead. The other three messages are the parser's own words and stay the same.

err.typeStatusWhat happenedWhat the client should do
entity.parse.failed400the body is not valid JSONfix the JSON
entity.too.large413the body is over the limit, 100 KB unless you set onesend less, or in parts
charset.unsupported415a charset in Content-Type that is not UTF-8send UTF-8
encoding.unsupported415a Content-Encoding the parser cannot undosend the body plain, or gzip

These errors come with err.expose set to true: the package that makes them, http-errors, marks an error below 500 as safe to show. Express's default handler reads that flag, and your own handler may too.

The limit is an option: express.json({ limit: "1mb" }). Set it to what the route really needs. A reading needs a few hundred bytes, and a limit stops a client from sending a hundred megabytes to a route that expects them.

Folding them into your shape

The parser's types are its own. Your API's answers have one shape, from the last section, so the handler translates: a table from each type to a code and a message of yours, and next(err) for anything that is not a parser error:

app.js

const express = require("express");
const app = express();
const PARSER_CODES = {
  "entity.parse.failed": ["INVALID_JSON", "the body is not valid JSON"],
  "entity.too.large": ["BODY_TOO_LARGE", "the body is over the limit"],
  "charset.unsupported": ["UNSUPPORTED_BODY", "send the body as UTF-8"],
  "encoding.unsupported": ["UNSUPPORTED_BODY", "send the body without a content encoding"],
};
app.use(express.json({ limit: "20b" }));
app.post("/r", (req, res) => res.status(201).json({ saved: req.body }));
app.use((err, req, res, next) => {
  const known = PARSER_CODES[err.type];
  if (!known) return next(err);
  res.status(err.status).json({ status: err.status, code: known[0], message: known[1] });
});
app.use((err, req, res, next) => res.status(500).json({ status: 500, code: "INTERNAL", message: "something broke on our side" }));
const server = app.listen(3000, async () => {
  const send = (body, headers) => fetch("http://localhost:3000/r", { method: "POST", headers: { "Content-Type": "application/json", ...headers }, body });
  for (const r of [await send("{bad", {}), await send('{"value":95,"note":"too long"}', {}), await send('{"a":1}', { "Content-Encoding": "foo" })]) {
    console.log(r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

400 {"status":400,"code":"INVALID_JSON","message":"the body is not valid JSON"}
413 {"status":413,"code":"BODY_TOO_LARGE","message":"the body is over the limit"}
415 {"status":415,"code":"UNSUPPORTED_BODY","message":"send the body without a content encoding"}

The first handler knows the four types and answers them in the API's shape. Anything else it passes on with next(err), to the second handler, which answers 500. Two handlers in a row is the subject of the next section.

Worked example 3

Check a reading's body fully and answer every problem at once, in the same shape as the parser's errors: a 400 with a code, a message and the list of problems.

What we have: a POST route for /readings that expects gauge, a string; value, a number from 0 to 200; and tags, a list

What we need: INVALID_JSON for broken JSON, INVALID_BODY with three details for a body that is wrong in three ways, and 201 for a good one

The plan: collect every problem in a list before throwing one HttpError with the list as its details; in the handler, turn the parser's two likely types into HttpErrors first, then answer every HttpError the same way

app.js

const express = require("express");
const app = express();
class HttpError extends Error {
  constructor(status, code, message, details) { super(message); this.status = status; this.code = code; this.details = details; }
}
app.use(express.json({ limit: "1kb" }));
app.post("/readings", (req, res) => {
  const body = req.body;
  const problems = [];
  if (typeof body.gauge !== "string" || body.gauge === "") problems.push("gauge must be a non-empty string");
  if (typeof body.value !== "number") problems.push("value must be a number");
  else if (body.value < 0 || body.value > 200) problems.push("value must be between 0 and 200");
  if (!Array.isArray(body.tags)) problems.push("tags must be a list");
  if (problems.length) throw new HttpError(400, "INVALID_BODY", `${problems.length} problem(s) with the body`, problems);
  res.status(201).json({ saved: body });
});
app.use((err, req, res, next) => {
  if (err.type === "entity.parse.failed") err = new HttpError(400, "INVALID_JSON", "the body is not valid JSON");
  else if (err.type === "entity.too.large") err = new HttpError(413, "BODY_TOO_LARGE", "the body is over the limit");
  const known = err instanceof HttpError;
  const status = known ? err.status : 500;
  res.status(status).json({ status, code: known ? err.code : "INTERNAL", message: known ? err.message : "something broke on our side", ...(err.details ? { details: err.details } : {}) });
});
const server = app.listen(3000, async () => {
  const send = (body) => fetch("http://localhost:3000/readings", { method: "POST", headers: { "Content-Type": "application/json" }, body });
  for (const r of [await send("{bad"), await send('{"gauge":"","value":250}'), await send('{"gauge":"boiler","value":95,"tags":["night"]}')]) {
    console.log(r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

400 {"status":400,"code":"INVALID_JSON","message":"the body is not valid JSON"}
400 {"status":400,"code":"INVALID_BODY","message":"3 problem(s) with the body","details":["gauge must be a non-empty string","value must be between 0 and 200","tags must be a list"]}
201 {"saved":{"gauge":"boiler","value":95,"tags":["night"]}}
  1. Lesson 02 taught the rule: check everything and answer every problem at once, so that the client fixes its body in one go. Here the list travels in details.
  2. The empty gauge, the value of 250 and the missing tags gave three problems in one answer; a client that sees them all fixes them all.
  3. The handler turned the parser's errors into HttpErrors before the common code, so that one answer shape serves the parser's errors and the route's own.
  4. The good body passed every check and was saved with 201.

400 INVALID_JSON, 400 INVALID_BODY with three details, then 201.

Check: Every failure answered in the same shape, and the valid body went through untouched.

Another way: keep the checks in a function, validateReading(body), that returns the list of problems, so that a PUT route can share it.

A path that fails: throwing at the first problem. The client learns of the empty gauge, fixes it, sends again, learns of the value, fixes it, sends again: three round trips for one body.

When you are stuck: The parser's error reaches the client in the wrong shape

Is the error handler after the routes, and does it read err.type? A parser's error has type, status and expose, but no code of yours.

Does the handler translate before the common code? Turn the parser's type into your own error first, then answer every error the same way.

Is the limit what you think? express.json() allows 100 KB unless you set limit; a 413 means the body was over it.

Your turn

A client sends a 2 MB JSON body to express.json() with no options. Which status and type does the parser's error carry?Tap to reveal
  1. The default limit is 100 KB.

413, with the type entity.too.large.

Why does the handler replace the message of an entity.parse.failed error?Tap to reveal
  1. Who wrote that message?

It is JSON.parse's own wording, which changes between versions; the API's message should not.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.use(express.json({ limit: "5b" }));
app.post("/", (req, res) => res.sendStatus(201));
app.use((err, req, res, next) => res.status(err.status).send(err.type));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/", { method: "POST", headers: { "Content-Type": "application/json" }, body: '{"a":1}' });
  console.log(r.status, await r.text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
413 entity.too.large
  1. The body is seven bytes; the limit is five.
  2. The parser passes an error with status 413 and its type.

It prints 413 entity.too.large.

Did you know?

A thousand fields at most

A form body has a second limit, on how many fields it holds. body-parser's documentation says that its urlencoded reader allows at most 1000 parameters by default, set by the option parameterLimit, and that a request with more gets 413. Its error type is parameters.too.many, one more type for this topic's table of translations.

Why it fits here: It answers this topic's question: besides the size limit, a form body may hold at most 1000 fields by default.

Source: body-parser on GitHub

Three names for 413

The code 413 has had three names. RFC 2616 of 1999 called it Request Entity Too Large, RFC 7231 of 2014 Payload Too Large, and RFC 9110 of 2022 Content Too Large. The parser's error type entity.too.large keeps the oldest name, from the time when HTTP called a request's body its entity.

Why it fits here: It explains this topic's entity.too.large: the name comes from 1999, when 413 was Request Entity Too Large.

Sources: RFC 2616: Hypertext Transfer Protocol, HTTP/1.1; RFC 7231: HTTP/1.1 Semantics and Content; RFC 9110: HTTP Semantics

In one line

A parser's error carries err.type (entity.parse.failed, entity.too.large, charset.unsupported, encoding.unsupported), err.status (400, 413, 415) and expose. Translate each type into your own code and message, replace JSON.parse's wording, set a limit that fits, and answer every validation problem at once in the same shape.

Several handlers, in order

At a glance

One error handler is often not enough. A logger, a translator and a final answer can each be one.

Error handlers run in the order written, like middleware. Each one either answers, or passes the error on with next(err), and a throw inside one lands in the next. One case needs care: an error that comes after the headers have gone. When res.headersSent is true, the handler returns next(err), and Express's default handler closes the connection, as nothing else can be done.

Take a guess: Is everything passed to next() treated as an error?

One error handler can do everything, but it grows. A logger, the answers for known errors, the answer for crashes: three jobs in one function. Express lets you write several error handlers, one after another, and an error walks down them as a request walks down middleware.

The rule is the same as for middleware. A handler that answers ends the walk. A handler that calls next(err) passes the error to the next error handler below. And a handler that throws passes its new error on, instead of crashing the app:

app.js

const express = require("express");
const app = express();
app.get("/known", (req, res) => { const e = new Error("the reading is out of range"); e.status = 422; throw e; });
app.get("/boom", (req, res) => { throw new Error("the boiler burst"); });
app.use((err, req, res, next) => { console.log("1. logged:", err.message); next(err); });
app.use((err, req, res, next) => {
  if (!err.status) return next(err);
  res.status(err.status).json({ error: err.message });
});
app.use((err, req, res, next) => { throw new Error("the handler itself broke on: " + err.message); });
app.use((err, req, res, next) => res.status(500).json({ error: err.message }));
const server = app.listen(3000, async () => {
  for (const p of ["/known", "/boom"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

1. logged: the reading is out of range
/known 422 {"error":"the reading is out of range"}
1. logged: the boiler burst
/boom 500 {"error":"the handler itself broke on: the boiler burst"}

Follow /known. The first handler logged it and called next(err). The second found a status on it and answered 422. The two handlers below never ran.

Now /boom. The first handler logged it. The second found no status and passed it on. The third threw, and Express caught that throw and passed the new error to the fourth, which answered 500 with the new message. A throw inside an error handler is not the end of the world: it lands in the next handler down.

In an error handlerWhat happens
it answersthe walk ends; handlers below never see this error
it calls next(err)the next error handler below receives the same error
it throws, or returns a rejected promisethe next error handler below receives the new error
there is no handler belowExpress's default handler answers

The error after the headers have gone

One case needs care. A route may have started its answer, with res.write, and then fail. The status line and the headers have already left the server. A handler cannot change the status now, and finishing the half-sent body with a JSON error would make a mess of both.

The Express documentation's advice is to hand such an error to the default handler, which closes the connection, so that the client knows the answer is broken:

app.js

const express = require("express");
const app = express();
app.get("/half", (req, res) => {
  res.write("first half,");
  throw new Error("the rest is lost");
});
app.use((err, req, res, next) => {
  console.log("headersSent:", res.headersSent);
  if (res.headersSent) return next(err);
  res.status(500).send("caught");
});
const server = app.listen(3000, async () => {
  try {
    const r = await fetch("http://localhost:3000/half");
    console.log(r.status, JSON.stringify(await r.text()));
  } catch (e) {
    console.log("client error:", e.message, "|", e.cause?.message ?? "");
  }
  server.close();
});

Terminal: node app.js 2>/dev/null

headersSent: true
client error: terminated | other side closed

res.headersSent was true, because res.write had sent the head. The handler returned next(err), the default handler closed the connection, and the client's fetch failed while reading the body: the error terminated, whose cause says other side closed. The client was not fooled into reading half a body as a whole one.

This is why an API builds its whole answer before sending any of it: one res.json at the end, after every check, never a res.write followed by work that may fail.

Answering twice

A handler that ignores res.headersSent and calls res.status(500).json(...) after a res.write gets ERR_HTTP_HEADERS_SENT, a second error, inside the error handler. The check comes first, in every handler: if (res.headersSent) return next(err).

Worked example 4

Split the API's error handling into three handlers: one that logs every error with its request, one that answers known errors, and one that answers crashes.

What we have: two routes, the 404 as an error, and three error handlers in a row

What we need: a log line for each failure, on the server, before the answer; 404 with a code for the missing gauge and the unknown address; 500 for the crash

The plan: the logger prints the method, the address and the error's code or class, then next(err); the second answers HttpErrors and passes on the rest; the third answers 500

app.js

const express = require("express");
const app = express();
class HttpError extends Error {
  constructor(status, code, message) { super(message); this.status = status; this.code = code; }
}
const gauges = { boiler: 95 };
app.get("/gauges/:name", (req, res) => {
  if (!Object.hasOwn(gauges, req.params.name)) throw new HttpError(404, "GAUGE_NOT_FOUND", `no gauge called ${req.params.name}`);
  res.json({ value: gauges[req.params.name] });
});
app.get("/crash", (req, res) => { throw new Error("a broken gear"); });
app.use((req, res, next) => next(new HttpError(404, "NO_ROUTE", `no route for ${req.method} ${req.originalUrl}`)));
app.use((err, req, res, next) => {
  console.log(`log: ${req.method} ${req.originalUrl} -> ${err.code ?? err.constructor.name}: ${err.message}`);
  next(err);
});
app.use((err, req, res, next) => {
  if (!(err instanceof HttpError)) return next(err);
  res.status(err.status).json({ code: err.code, message: err.message });
});
app.use((err, req, res, next) => res.status(500).json({ code: "INTERNAL", message: "something broke on our side" }));
const server = app.listen(3000, async () => {
  for (const p of ["/gauges/boiler", "/gauges/fan", "/crash", "/nowhere"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

/gauges/boiler 200 {"value":95}
log: GET /gauges/fan -> GAUGE_NOT_FOUND: no gauge called fan
/gauges/fan 404 {"code":"GAUGE_NOT_FOUND","message":"no gauge called fan"}
log: GET /crash -> Error: a broken gear
/crash 500 {"code":"INTERNAL","message":"something broke on our side"}
log: GET /nowhere -> NO_ROUTE: no route for GET /nowhere
/nowhere 404 {"code":"NO_ROUTE","message":"no route for GET /nowhere"}
  1. The log line came first for each failure, printed while the server handled the request, then the client's line.
  2. The second handler used instanceof to keep only the errors made on purpose. The crash, a plain Error, went on to the third.
  3. Each handler has one job, and the order is the order of the jobs: log, then answer the known, then answer the rest.

Three log lines on the server; 404 GAUGE_NOT_FOUND, 500 INTERNAL and 404 NO_ROUTE for the client.

Check: Every failure was logged once and answered once, by the right handler.

Another way: have the logger add a request id to each line, and send the same id to the client in the answer, so that a client's report can be found in the log.

A path that fails: putting the catch-all 500 handler first. It answers everything, and the logger and the known-errors handler below it never run.

Worked example 5

Give every request a number, print it in the log line, and send it back in the error answer, so that a client's report can be matched with the server's log.

What we have: a counter in a middleware that puts req.id on every request, a logging handler and an answering handler

What we need: a log line with #1 and #2 on the server, and a requestId of 1 and 2 in the two error answers

The plan: the first middleware adds one to the count and stores it on req; the logger prints it; the answering handler sends it along with the code, and keeps the crash's message to the log

app.js

const express = require("express");
const app = express();
class HttpError extends Error {
  constructor(status, code, message) { super(message); this.status = status; this.code = code; }
}
let count = 0;
app.use((req, res, next) => { req.id = ++count; next(); });
app.get("/gauges/:name", (req, res) => { throw new HttpError(404, "GAUGE_NOT_FOUND", `no gauge called ${req.params.name}`); });
app.get("/crash", (req, res) => { throw new Error("a broken gear"); });
app.use((err, req, res, next) => {
  console.log(`log #${req.id}: ${req.method} ${req.originalUrl} ${err.code ?? err.constructor.name}: ${err.message}`);
  next(err);
});
app.use((err, req, res, next) => {
  const known = err instanceof HttpError;
  res.status(known ? err.status : 500).json({ code: known ? err.code : "INTERNAL", requestId: req.id });
});
const server = app.listen(3000, async () => {
  for (const p of ["/gauges/fan", "/crash"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

log #1: GET /gauges/fan GAUGE_NOT_FOUND: no gauge called fan
/gauges/fan 404 {"code":"GAUGE_NOT_FOUND","requestId":1}
log #2: GET /crash Error: a broken gear
/crash 500 {"code":"INTERNAL","requestId":2}
  1. The id was made before anything else ran, so every handler below could read it from req.
  2. The crash's answer carried the code INTERNAL and the id, and nothing of the message. The message is in the log, next to the same id, where the owner can find it.
  3. A real API makes the id random and long, or takes one the client sent in a header, so that it is unique across many servers.

log #1 and #2 on the server; requestId 1 and 2 in the answers.

Check: Each answer's id matches one log line, which is all a support engineer needs.

Another way: send the id in a header, X-Request-Id, on every answer, successes included, and accept one from the client's header when it sends one.

A path that fails: making the id in the answering handler. The logger above it would have nothing to print, and a success would never carry an id.

When you are stuck: The wrong handler answers

Which handler comes first? An error walks down from the place it started; the first handler that answers wins.

Did a handler forget next(err)? A handler that neither answers nor passes on leaves the request waiting, like a middleware without next.

Is a handler answering after res.write? Check res.headersSent first, and return next(err) when it is true.

Your turn

An error handler throws a new error. Where does the new error go?Tap to reveal
  1. Express catches throws in handlers too.

To the next error handler below; with none, to Express's default handler.

Why should a handler hand an error to the default handler when res.headersSent is true?Tap to reveal
  1. Think about what has already left the server.

The status and the headers have gone; the default handler closes the connection, so the client knows the answer is broken.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/", (req, res) => { throw new Error("one"); });
app.use((err, req, res, next) => next(new Error(err.message + " two")));
app.use((err, req, res, next) => res.status(500).send(err.message));
const server = app.listen(3000, async () => {
  console.log(await (await fetch("http://localhost:3000/")).text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
one two
  1. The first handler passes a new error on with next.
  2. The second answers with the new message.

It prints one two.

Did you know?

One string is not an error

Anything passed to next is an error, with one exception. Express's guide says that if you pass anything to next() except the string 'route', Express treats the request as an error and skips every remaining handler that is not an error handler. So next("oops") starts the error chain, while next("route") moves on to the next route.

Why it fits here: It answers this topic's question: next() with any value but 'route' sends the request down the error chain.

Source: Express: Error handling

Express 5 checks the status

Express 5 guards the status code. Its migration guide says that res.status accepts only integers from 100 to 999, following Node's own rule, and throws for anything else: res.status(99) throws. So a handler that copies err.status onto the answer checks it first, or a strange status becomes a second error inside the first.

Why it fits here: It warns this topic's handlers: an invalid err.status makes res.status throw, inside the error handler itself.

Source: Express: Migrating to Express 5

In one line

Error handlers run in order, like middleware: one answers, or passes the error on with next(err), and a throw inside one lands in the next; when res.headersSent is true, return next(err) and let the default handler close the connection.

The failures that are not errors

At a glance

Some failures throw nothing at all. A route can stay silent for ever, and nothing calls an error handler.

Such failures need bells. A timer for each request answers 503 when a route never answers, and AbortSignal.timeout gives the client its own patience. Inside every callback, an error goes to next(err), and every promise needs an await or a catch. A throw outside the request's path, or a rejection that nobody handles, ends the whole process. Each bell turns silence into an answer.

Take a guess: How can a platform tell that a server has hung, when it throws nothing?

Every failure so far threw something, and a handler caught it. The worst failures throw nothing. A route that never answers raises no error: the client waits, the connection stays open, and the server's log is silent. A throw inside a timer reaches no handler. A promise nobody waited for fails in the dark.

This section gives each one a bell.

A route that never answers

A handler that neither answers nor calls next, from lesson 04, leaves the request waiting. A database that never replies, or a loop that waits on a lock, does the same. The cure is a bell: a timer set when the request arrives, cleared when the answer goes out, and ringing with an error if the answer is late:

app.js

const express = require("express");
const app = express();
app.use((req, res, next) => {
  const bell = setTimeout(() => {
    const e = new Error("the bench did not answer in time");
    e.status = 503;
    next(e);
  }, 100);
  res.on("finish", () => clearTimeout(bell));
  next();
});
app.get("/fast", (req, res) => res.send("quick"));
app.get("/slow", (req, res) => {});
app.use((err, req, res, next) => res.status(err.status ?? 500).json({ error: err.message }));
const server = app.listen(3000, async () => {
  for (const p of ["/fast", "/slow"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

/fast 200 quick
/slow 503 {"error":"the bench did not answer in time"}

The middleware set a timer of 100 milliseconds for every request, and listened for the response's finish event to clear it. The fast route finished long before the bell. The slow one never answered, so the bell rang and called next with an error of status 503 Service Unavailable: the server is here, but cannot serve this request now.

A real bell is longer, a few seconds, and 503 is the honest status for it. The route that never answered is still broken, and the log should say which route rang the bell, so that someone fixes it.

The client's own patience

A client should not trust the server to ring a bell. fetch takes a signal, and AbortSignal.timeout(ms) makes one that gives up after a time. The fetch then fails with an error named TimeoutError, and the server sees the connection close:

app.js

const express = require("express");
const app = express();
app.get("/slow", (req, res) => {
  req.on("close", () => console.log("server: the client gave up"));
});
const server = app.listen(3000, async () => {
  try {
    await fetch("http://localhost:3000/slow", { signal: AbortSignal.timeout(200) });
  } catch (e) {
    console.log("client:", e.name, "|", e.message);
  }
  server.close();
});

Terminal: node app.js

client: TimeoutError | The operation was aborted due to timeout
server: the client gave up

The client gave up after 200 milliseconds, and the request's close event fired on the server, where the route was still doing nothing. Both sides should have a timeout: the server's bell protects the server from a stuck route, and the client's signal protects the client from a stuck server, or a broken network, which no bell on the server can see.

A throw that nobody catches

Express catches a throw inside a route, and a rejected promise from an async handler. It cannot catch a throw inside a timer or a callback, because that code runs later, outside the request's path. Such a throw ends the whole process:

app.js

const express = require("express");
const app = express();
app.get("/late", (req, res) => {
  setTimeout(() => { throw new Error("thrown after the answer, outside the request"); }, 50);
  res.send("sent");
});
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/late");
  console.log("client:", await r.text());
  server.close();
});

Terminal: node app.js 2>/dev/null; echo "exit $?"

client: sent
exit 1

The answer went out, then the timer fired, threw, and nobody was there. Node printed the error to the error stream, hidden here, and ended the process with the exit status 1, which echo "exit $?" shows. Every request in flight died with it. The fix is the one from the second section: inside a callback, call next(err), or catch and report, never throw.

The same happens to a promise that is neither awaited nor given a catch. Node treats a rejection nobody handles as a crash:

app.js

const express = require("express");
const app = express();
app.get("/", (req, res) => {
  Promise.reject(new Error("a promise nobody waited for"));
  res.send("sent");
});
const server = app.listen(3000, async () => {
  await fetch("http://localhost:3000/");
  server.close();
});

Terminal: node app.js 2>/dev/null; echo "exit $?"

exit 1

Node noticed the rejection as soon as the route returned, and ended the process with the exit status 1; in Node itself that happens before the answer even reaches the client. Await every promise, or give it a catch.

When the process does die

A server in production runs under something that restarts it: a process manager such as pm2, a systemd unit, or a container's restart policy. A crash then costs the requests in flight and a second of downtime, not the night. That is a safety net, not a plan: the log must say why it crashed, and the cause must be fixed.

Node's process object can listen for uncaughtException and unhandledRejection; the right use is to log and exit, not to carry on with a process in an unknown state.

FailureWhat you seeThe fix
a route that never answersthe client waits; no error anywherea bell: a timer per request that answers 503
a server that never answersthe client waitsa signal on the client: AbortSignal.timeout
a throw inside a timer or callbackthe process ends with status 1call next(err) or catch inside the callback
a promise nobody waited forthe process ends with status 1await it, or give it a catch

Worked example 6

Make the bell polite: a route that answers in time passes, a stuck one gets 503 with Retry-After, so that a well-behaved client knows when to try again.

What we have: a bell of 100 milliseconds, a route that answers after 40, and a route that never answers

What we need: 200 for the first, 503 with Retry-After: 5 for the second

The plan: put the header on the error as err.headers; in the handler, copy err.headers onto the answer with res.set before answering

app.js

const express = require("express");
const app = express();
app.use((req, res, next) => {
  const bell = setTimeout(() => {
    const e = new Error("the bench did not answer in time");
    e.status = 503;
    e.headers = { "Retry-After": "5" };
    next(e);
  }, 100);
  res.on("finish", () => clearTimeout(bell));
  next();
});
app.get("/medium", (req, res) => setTimeout(() => res.send("done in time"), 40));
app.get("/stuck", (req, res) => {});
app.use((err, req, res, next) => {
  if (err.headers) res.set(err.headers);
  res.status(err.status ?? 500).json({ error: err.message });
});
const server = app.listen(3000, async () => {
  for (const p of ["/medium", "/stuck"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, r.headers.get("retry-after"), await r.text());
  }
  server.close();
});

Terminal: node app.js

/medium 200 null done in time
/stuck 503 5 {"error":"the bench did not answer in time"}
  1. /medium answered after 40 milliseconds, the finish event cleared the bell, and no Retry-After was sent: the header belongs to the failure only.
  2. /stuck never answered. At 100 milliseconds the bell made the error, with its status and its header, and the handler copied the header onto the answer.
  3. Retry-After: 5 asks the client to wait five seconds before trying again, which stops a hundred clients from retrying at once.

200 done in time, then 503 with Retry-After: 5.

Check: The bell rang only for the stuck route, and the answer carried the advice a client needs.

Another way: log the route that rang the bell, with req.method and req.originalUrl, so that the stuck route is found the next morning.

A path that fails: setting the bell without clearing it on finish. The timer would fire after a good answer too, and next(err) after an answer gives a second error, ERR_HTTP_HEADERS_SENT, in the handler.

When you are stuck: Requests hang, or the process keeps dying

Is there a bell? Without one, a stuck route shows nothing; add the timer middleware and read its log line.

Does the process exit with status 1 after a request? Look for a throw inside a timer, a stream's listener or a callback, or a promise without await or catch.

Is a handler answering after the bell rang? Clear the bell on finish, and check res.headersSent in the handler.

Your turn

A route starts a timer, and the timer's callback throws. Which handler receives the error?Tap to reveal
  1. The callback runs outside the request's path.

None: the process ends with the exit status 1. Call next(err) inside the callback instead.

Which status does the bell answer for a route that did not answer in time, and which header can it add?Tap to reveal
  1. The server is here, but cannot serve this request now.

503 Service Unavailable, with Retry-After.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/", (req, res) => {});
const server = app.listen(3000, async () => {
  try {
    await fetch("http://localhost:3000/", { signal: AbortSignal.timeout(100) });
  } catch (e) {
    console.log(e.name);
  }
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
TimeoutError
  1. The route never answers.
  2. The signal gives up after 100 milliseconds, and fetch fails with a TimeoutError.

It prints TimeoutError.

Did you know?

Liveness and readiness

A server that hangs throws nothing, so platforms check on it from outside. Express's guide on health checks gives Kubernetes as an example, with two checks: liveness, which decides when to restart a container, and readiness, which decides when it may take traffic. Kubernetes' documentation adds that a liveness probe can catch a deadlock, where an application runs but makes no progress.

Why it fits here: It answers this topic's question: a liveness check asks a server from outside, and restarts it when it has hung.

Sources: Express: Health checks and graceful shutdown; Kubernetes documentation: Liveness, readiness and startup probes

Retry-After, in seconds or as a date

Retry-After has two forms. RFC 9110 says its value can be an HTTP-date or a number of seconds to wait. With 503, it tells how long the service is expected to be unavailable; with a redirect, it gives the least time to wait before following it. So Retry-After: 120 and a date two minutes ahead say the same thing.

Why it fits here: It adds to this topic's Retry-After: it may hold seconds or a date, and it works with redirects too.

Source: RFC 9110: HTTP Semantics

In one line

The failures that throw nothing need bells. A timer per request answers 503 when a route never answers, AbortSignal.timeout gives the client its own patience, next(err) belongs inside every callback, and every promise needs an await or a catch. A throw outside the request's path, or a rejection nobody handles, ends the process.

Where it is used

Every API that people rely on fails in the ways this lesson showed, many times a day. Here is where each idea does its work.

What you learnedWhere it is usedA real example
the default handler, hidden in productionevery Express appNODE_ENV=production on every server that faces the world
one error shape with a codeevery public APIa payment API whose errors carry codes such as card_declined
parser errors and limitsevery API that takes bodiesa 413 from an upload route with a limit of a few megabytes
validation with every problem at onceevery form and every API that takes dataa sign-up answer that lists each field's problem
handlers in order, with a logger firstevery server in productionan error logger that sends each failure to a dashboard
bells and timeoutsevery service that calls anothera 503 with Retry-After when a database is slow

The shape of this lesson's answers is close to the one that the standard called Problem Details for HTTP APIs (RFC 9457) describes, with its type, title, status and detail. Many APIs use that exact shape; the ideas are the same.

In the Couriers' Yard, the slip on every returned parcel is the error answer, the yard's own book is the server's log, and the bell on a silent bench is the timeout.

Mistakes and debugging

These are the mistakes that beginners make most with errors, each with the way to see it and the fix.

1. A string instead of an Error

next("jammed") reaches the handler, but as a string, which has no fields:

app.js

const express = require("express");
const app = express();
app.get("/", (req, res, next) => next("jammed"));
app.use((err, req, res, next) => res.status(500).send(`message: ${err.message}, status: ${err.status}`));
const server = app.listen(3000, async () => {
  console.log(await (await fetch("http://localhost:3000/")).text());
  server.close();
});

Terminal: node app.js

message: undefined, status: undefined

err.message and err.status are both undefined, and there is no stack to say where it came from. Throw Error objects, or your HttpError, and nothing else.

2. The stack sent to the client

A handler that answers with err.stack, or err.message for a crash, tells the world the server's file names, line numbers and sometimes a password in a connection string. The message of a crash goes to the log; the client gets a plain sentence and, at most, a request id to quote.

3. try and catch in every route

Wrapping each route in try and catch and answering 500 from each one works, until a route forgets. Express catches throws and rejected promises for you; one handler at the end does the job once, in one shape, with one log line.

4. A throw inside a callback

A callback for a timer, a stream or a database runs outside the request's path, and a throw there ends the process, as the last section showed. Inside a callback, call next(err), or catch the error and answer.

5. The catch-all handler first

Handlers run in order. A 500 catch-all above the logger and the known-errors handler answers everything, and the two below never run. Put the catch-all last.

6. Answering after the head has gone

A handler that sends JSON after a res.write gets ERR_HTTP_HEADERS_SENT. Check res.headersSent first and return next(err), and build whole answers before sending any part of them.

The debugging corner: find where it started

Print err.stack on the server, in the first error handler: its second line names the file and line that threw. For a string or a number, there is no stack, which is a reason to throw Errors.

When a client reports a failure, the log should let you find it: a request id in the log line and in the answer, or the method, the address and the time.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

app.js

const express = require("express");
const app = express();
class HttpError extends Error {
  constructor(status, code, message, details) { super(message); this.status = status; this.code = code; this.details = details; }
}
const gauges = { boiler: 95 };
app.use((req, res, next) => {
  const bell = setTimeout(() => next(new HttpError(503, "TIMEOUT", "the server did not answer in time")), 100);
  res.on("finish", () => clearTimeout(bell));
  next();
});
app.use(express.json({ limit: "1kb" }));
app.get("/gauges/:name", (req, res) => {
  if (!Object.hasOwn(gauges, req.params.name)) throw new HttpError(404, "GAUGE_NOT_FOUND", `no gauge called ${req.params.name}`);
  res.json({ value: gauges[req.params.name] });
});
app.post("/readings", (req, res) => {
  const problems = [];
  if (typeof req.body.value !== "number") problems.push("value must be a number");
  if (problems.length) throw new HttpError(400, "INVALID_BODY", "the body has problems", problems);
  res.status(201).json({ saved: req.body });
});
app.get("/crash", (req, res) => { throw new Error("a broken gear"); });
app.get("/stuck", (req, res) => {});
app.use((req, res, next) => next(new HttpError(404, "NO_ROUTE", `no route for ${req.method} ${req.originalUrl}`)));
app.use((err, req, res, next) => {
  if (err.type === "entity.parse.failed") err = new HttpError(400, "INVALID_JSON", "the body is not valid JSON");
  if (res.headersSent) return next(err);
  const known = err instanceof HttpError;
  if (!known) console.log("log:", req.method, req.originalUrl, err.message);
  const status = known ? err.status : 500;
  res.status(status).json({ status, code: known ? err.code : "INTERNAL", message: known ? err.message : "something broke on our side", ...(err.details ? { details: err.details } : {}) });
});
const server = app.listen(3000, async () => {
  const url = "http://localhost:3000";
  const post = (body) => fetch(url + "/readings", { method: "POST", headers: { "Content-Type": "application/json" }, body });
  const answers = [await fetch(url + "/gauges/boiler"), await fetch(url + "/gauges/fan"), await post("{bad"), await post('{"value":"hot"}'), await fetch(url + "/crash"), await fetch(url + "/nowhere"), await fetch(url + "/stuck")];
  for (const r of answers) console.log(r.status, await r.text());
  server.close();
});

Terminal: node app.js

log: GET /crash a broken gear
200 {"value":95}
404 {"status":404,"code":"GAUGE_NOT_FOUND","message":"no gauge called fan"}
400 {"status":400,"code":"INVALID_JSON","message":"the body is not valid JSON"}
400 {"status":400,"code":"INVALID_BODY","message":"the body has problems","details":["value must be a number"]}
500 {"status":500,"code":"INTERNAL","message":"something broke on our side"}
404 {"status":404,"code":"NO_ROUTE","message":"no route for GET /nowhere"}
503 {"status":503,"code":"TIMEOUT","message":"the server did not answer in time"}
When you seeIt meansDo
Express's HTML error pageno handler of yours answeredan error handler with four parameters, last in the line
a stack in the client's answerthe app runs in development, or a handler sends err.stackNODE_ENV=production; send a plain sentence for crashes
err.message undefined in a handlernext was given a string or a numberthrow Error objects, or your HttpError
err.type on an errora parser's error: parse.failed, too.large, charset or encodingtranslate it into your own code and message
a request that never endsa route that neither answers nor calls nexta bell per request that answers 503; a timeout on the client
the process exits with status 1a throw in a callback, or a promise nobody awaitednext(err) in the callback; await or catch the promise
ERR_HTTP_HEADERS_SENT in a handleran answer after res.write, or after the bell rangif (res.headersSent) return next(err); clear the bell on finish

The story: How a good yard fails

Now every failure leaves the yard on the same kind of slip. It carries a number, a short code that the sender's machines can read, and a sentence that a person can read. A parcel packed wrongly also gets the list of everything wrong with it. A burst crate gets a plain apology and nothing more; the full story goes into the yard's own book.

A parcel for a bench that does not exist gets the same slip as any other failure. A bench that never answers is given a bell: when it rings, the courier is sent away with a slip instead of waiting all day.

The Yardmaster reads the day's book, three failures, each explained. "Tomorrow," she says, "a line that stays open: both ends talking, with no parcel at all."

Reagents gathered: error handler, status, error code, validation error, default handler, timeout.

Sources

  • The Express documentation (CC BY-SA 3.0 US (the site's footer, read 2026-11-15); facts and ideas only)
  • The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
  • MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)