Error Handling and Consistent Error Responses
Express 5 passes an error from any route, async ones included, to error-handling middleware with four parameters, and a 404 handler after the routes catches every unknown path, so every error the API sends has one JSON shape and no caller ever sees an HTML page or a stack trace.
Journeyman · Node.js · REST API · Updated
After this lesson you can
- Handle errors from async routes with error-handling middleware that has four parameters
- Answer unknown paths with a 404 handler placed after every route
- Send every error in one JSON shape, with a status, a title, a detail and any field problems, and never a stack trace
Key takeaways
- Express 5 catches an error thrown in an async route and passes it on. With no handler of your own, it answers with an HTML page that shows the stack trace.
- Error-handling middleware has four parameters, (err, req, res, next). Express knows it by the four, and it goes after every route.
- A 404 handler is middleware with no path, placed after every route, so only the requests no route answered reach it.
- Every error the API sends has one shape, with status, title, detail and, for a body that breaks the rules, problems. It's modeled on RFC 9457's problem details.
- Log the whole error on the server, and send the caller a short message. A stack trace shows your folders and code to anyone who asks.
A phone app that calls your API has to show something when a call goes wrong. Its developer writes that code once, for the error answers you told them about, and any other answer turns into a blank screen. Errors that all look the same, and a server that keeps running when its own code fails, are what make an API something other people can build on.
Spoke & Chain's API grew one route at a time, and it now answers errors four different ways. A missing ticket gets { "message": … }. A ticket that breaks the rules gets { "message": …, "problems": [ … ] }. An address no route knows, such as GET /bikes, gets an HTML page from Express that says Cannot GET /bikes. And when a route's own code fails, the caller gets the worst answer of all.
Express 5 passes async errors on
The shop moved its server to a new laptop, and the file of old tickets didn't come along. This route reads it:
app.get("/tickets/archive", async (req, res) => {
const text = await readFile("archive.json", "utf8");
res.json(JSON.parse(text));
});
readFile throws, because there's no archive.json. Express 5 catches an error from any route, async ones included, and passes it on. With no error handler of your own, Express's built-in one answers:
GET /tickets/archive
HTTP/1.1 500 Internal Server Error
content-type: text/html; charset=utf-8
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error: ENOENT: no such file or directory, open 'C:\Users\Sam\nodejs-course\spoke-and-chain\archive.json'<br> at async open (node:internal/fs/promises:697:25)<br> at async readFile (node:internal/fs/promises:1348:14)<br> at async file:///C:/Users/Sam/nodejs-course/spoke-and-chain/app.js:8:16</pre>
</body>
</html>
The server survived, but the phone app got a web page instead of JSON, and inside it is the stack trace: the list of functions that were running when the error happened, with your user name, your folders and your file names. That's a map of your server for anyone who asks, and it means nothing to the person holding the phone. (Express 4 didn't catch errors from async routes at all: the same error stopped the whole server. Older code wraps each async route in try/catch for that reason.)
One error shape for the whole API
Before handling the errors, decide what every error answer looks like. A standard, RFC 9457, Problem Details for HTTP APIs, names the parts most APIs agree on, and this course's shape borrows three of them, plus a list for field problems:
status: the status code, repeated in the body, so it survives when the body is saved or logged.title: the status code's name, such as"Not Found".detail: what went wrong this time, in a sentence a person can read.problems: only for a body that breaks the rules, the{ field, message }list from Validating with Zod.
One small function sends it. STATUS_CODES, from Status Codes and Headers, already knows every title:
import { STATUS_CODES } from "node:http";
function sendProblem(res, status, detail, problems) {
const body = { status, title: STATUS_CODES[status], detail };
if (problems !== undefined) {
body.problems = problems;
}
res.status(status).json(body);
}
From here on, every error this course's APIs send has this shape. It replaces the { "message": … } bodies of the chapters before: message becomes detail, and status and title come with it. The routes change one line each, such as sendProblem(res, 404, `There's no ticket ${req.params.id}.`) and sendProblem(res, 400, "The ticket isn't valid.", toProblems(result.error.issues)).
Error-handling middleware: four parameters
Middleware usually takes (req, res, next). Error-handling middleware takes four, (err, req, res, next), and that's how Express tells them apart: when an error happens, Express skips the ordinary middleware and routes, and calls the next function with four parameters, with the error as err. It goes after every route:
app.use((err, req, res, next) => {
if (err.type === "entity.parse.failed") {
sendProblem(res, 400, "The body isn't valid JSON.");
return;
}
console.error(err);
sendProblem(res, 500, "Something went wrong on our side.");
});
Keep next in the list even though this handler doesn't call it: with three parameters, Express would treat it as ordinary middleware and never hand it an error. express.json() marks a body that isn't valid JSON with type set to "entity.parse.failed"; that's the caller's mistake, so it's a 400. Anything else is the server's own failure: a 500. console.error(err) writes the whole error, stack trace included, to the server's terminal, where you'll read it. The caller gets one calm sentence.
A 404 for every unknown path
A request that no route answers falls through to whatever comes next. Middleware with no path runs for every request that gets that far, so placed after every route, it catches exactly the unknown ones:
app.use((req, res) => {
sendProblem(res, 404, `There's nothing at ${req.path}.`);
});
The order in app.js matters: express.json() first, then every route, then the 404 handler, then the error handler last.

With all of it in place, five requests that go wrong, each answer's status line and body:
GET /tickets/99
HTTP/1.1 404 Not Found
{"status":404,"title":"Not Found","detail":"There's no ticket 99."}
POST /tickets {}
HTTP/1.1 400 Bad Request
{"status":400,"title":"Bad Request","detail":"The ticket isn't valid.","problems":[{"field":"customer","message":"Invalid input: expected string, received undefined"},{"field":"bike","message":"Invalid input: expected string, received undefined"},{"field":"problem","message":"Invalid input: expected string, received undefined"}]}
POST /tickets { "customer": Lena }
HTTP/1.1 400 Bad Request
{"status":400,"title":"Bad Request","detail":"The body isn't valid JSON."}
GET /bikes
HTTP/1.1 404 Not Found
{"status":404,"title":"Not Found","detail":"There's nothing at /bikes."}
GET /tickets/archive
HTTP/1.1 500 Internal Server Error
{"status":500,"title":"Internal Server Error","detail":"Something went wrong on our side."}
Meanwhile, the server's terminal shows the whole error for the last one, starting:
Error: ENOENT: no such file or directory, open 'C:\Users\Sam\nodejs-course\spoke-and-chain\archive.json'
Every answer is JSON, every one has the same shape, and the details stay where only you can read them.
Check yourself
2 questions to try on the lesson page.
So what
One error shape means a caller writes its error handling once, and an error handler that logs the details but answers calmly means a bug in your code never becomes a map of your server.