In the last video, a toy function with four parameters, placed below the routers, caught a thrown NotFoundError and a rejected ConflictError and turned each one into a row of the failure table. The wall’s real API still has nothing like it. Ask it for problem 42 and you get Express’s HTML 500. Broken JSON and unknown paths still get HTML pages too.
In this lesson, you’ll write the API’s one error handler, and you’ll make every failure in the table reach it: the store’s errors, the ones express.json() raises, paths no route matches, and the refusals validate() sends today. Start with the failure nobody planned for, because that’s the one a handler has to catch most of all.
Catch an Error Nobody Expected
The store’s errors are ones you designed. A real bug or a failed disk write is different, because no code anticipates it. To have one on demand, plant it. In routes/problems.ts, add a deliberate throw to the POST /problems handler, right before the save:
routes/problems.ts
async (req, res) => {
const fields: NewProblem = res.locals.body;
throw new Error("Simulated save failure");
const problem = await store.create({ ...fields, retired: false });
res.status(201).location(`/problems/${problem.id}`).json(problem);
},
TypeScript accepts this, and the store and problems.json stay untouched. Now send Ines’s next problem, Moon Walk:
$ curl -i -H "Content-Type: application/json" \
-d '{"name":"Moon Walk","colour":"black","grade":"V6",
"setOn":"2026-11-20"}' http://localhost:3000/problems
HTTP/1.1 500 Internal Server Error
...
Content-Type: text/html; charset=utf-8
...
<!DOCTYPE html>
...
<pre>Error: Simulated save failure<br> at
file:///.../routes/problems.ts:57:11<br>
...
The command and the page are wrapped and cut here for display. It’s Express’s default page, with the stack trace. Replace it the way the video’s toy did, with a function that takes four parameters, the error first, registered below the routers. Write the real one at the bottom of app.ts, with two new imports:
app.ts
import type { NextFunction, Request, Response } from "express";
// ...
import { toErrorResponse } from "./responses.ts";
// ...
app.use("/log", logRouter);
app.use(
(error: unknown, req: Request, res: Response, next: NextFunction) => {
const { status, body } = toErrorResponse(error);
res.status(status).json(body);
},
);
Read the body once more. Nothing calls next, and the video’s toy never called it either. An unused parameter looks like leftover code, so tidy it away. Delete next and NextFunction, and the handler fits on fewer lines:
app.ts
import type { Request, Response } from "express";
// ...
app.use((error: unknown, req: Request, res: Response) => {
const { status, body } = toErrorResponse(error);
res.status(status).json(body);
});
npm run check still passes. Before you send Moon Walk again, predict what curl gets back. Then send it, and also ask for a path that has no route at all:
$ curl -i http://localhost:3000/walls
Moon Walk gets the same HTML 500 as before. The path with no route, which used to get a 404, now gets a 500 as well:
$ curl -i http://localhost:3000/walls
HTTP/1.1 500 Internal Server Error
...
Content-Type: text/html; charset=utf-8
...
<!DOCTYPE html>
...
<pre>TypeError: res.status is not a function<br> at
file:///.../app.ts:23:7<br>
...
Express decides whether a function handles errors by counting its declared parameters, the function’s length. Four parameters make an error handler. Fewer parameters make ordinary middleware, which an error skips on its way down the chain, so the planted error fell through to Express’s default page.
For /walls, no route answered, so the request reached your function as ordinary middleware, called with (req, res, next). Your error got the request, your req got the response, and your res got next, which has no status() method. TypeScript can’t catch this, because Express’s types let an error handler declare fewer parameters than four.
So next wasn’t leftover code. Its place in the list is what makes the function an error handler. Put it back, and give it a job:
app.ts
import type { NextFunction, Request, Response } from "express";
// ...
app.use(
(error: unknown, req: Request, res: Response, next: NextFunction) => {
if (res.headersSent) {
return next(error);
}
const { status, body } = toErrorResponse(error);
res.status(status).json(body);
},
);