The Bookshop app fails to load reviews, and the screen shows strange text: TypeError, then a list of server folder paths and line numbers. The shopper understands none of it. Meanwhile, anyone with bad intentions has just got a map of your server. A request that fails is normal. The trouble is in how the server answers it.
Error handling in an API means answering a failed request properly. It takes care of three things: the right status code, the same error body shape on every endpoint, and no details from inside the server in the answer. Take the departures board at an airport. A flight in trouble is always written the same way: the flight code, a status (DELAYED, CANCELLED), and one sentence for the passengers. Passengers don't need to know which bolt broke. The details go in the engineers' logbook, not on the board. In an API, the board is the error body sent to the client, and the engineers' logbook is the server log (records on the server that only developers read).
Status codes: 4xx is the client's fault, 5xx the server's
The first digit of a status code already says who has to act:
- 4xx (400 to 499): a client-side error. The request needs fixing. Sending the same request again usually gives the same result. There are three exceptions.
429(too many requests): wait as long as theRetry-Afterheader says, then try again.408(the server ran out of time waiting for the request): trying again is allowed.401: log in first, then send it again. - 5xx (500 to 599): a server-side error. The client did nothing wrong. Trying again later may work.
The statuses you will use most:
| Status | When | Example at Bookshop |
|---|---|---|
400 Bad Request |
the request is broken, it can't be read | a JSON body whose curly brace is never closed |
401 Unauthorized |
not recognised yet | GET /profile with no token |
403 Forbidden |
logged in, but not permitted | Siti (a customer) deleting a book |
404 Not Found |
what was asked for doesn't exist | GET /books/99 |
409 Conflict |
clashes with data that already exists | adding a book whose title is already listed |
422 Unprocessable Content |
readable, but breaks the rules | a price of -5000 |
500 Internal Server Error |
a bug on the server | book.reviews turns out to be undefined |
503 Service Unavailable |
the server can't serve for a while | the database is down |
A user who is logged in but has no right to a resource is answered 403, not 401.
One error shape for every endpoint
If every route writes its own error ({"error": "..."} here, {"message": "..."} there, {"err": true} somewhere else), the frontend has to guess each shape. Pick one shape and use it on every endpoint. Here are two common shapes, both for the same mistake: the book that was asked for doesn't exist.
The simple shape, which the exercise also uses:
{ "error": { "code": "NOT_FOUND", "message": "Book not found" } }
codeis a fixed code for programs to read. The frontend only has to writeif (body.error.code === "NOT_FOUND"), so it doesn't depend on the sentence inmessage.messageis a sentence for people, and may change any time.
Problem Details (RFC 9457) is the official standard for errors in HTTP APIs. An RFC is an internet standards document, and 9457 is its number. This shape is sent with the header Content-Type: application/problem+json:
{
"type": "https://api.bookshop.test/problems/not-found",
"title": "Not Found",
"status": 404,
"detail": "Book 99 does not exist.",
"instance": "/books/99"
}
type: an address (URI) that serves as the name of the kind of error. That address is often its documentation page too. When there's nothing to say beyond the status, it'sabout:blank.title: a short summary of the kind of error, the same for every occurrence of the sametype.status: the same number as the HTTP status.detail: an explanation of this particular occurrence.instance: points at this particular occurrence, for example the request's path.- Extra fields are allowed, for example per-field
errorsfrom the Input Validation lesson.
Both are good. What matters: one shape for every endpoint.
A central error handler
In Express, a route only has to throw its error: the route's code stops, and the error is handed somewhere else. That place is one special middleware registered at the very end, called the error handler. The error handler answers every error:
class HttpError extends Error {
constructor(status, code, message) {
super(message);
this.status = status;
this.code = code;
}
}
app.get("/books/:id", (req, res) => {
const book = books.find((b) => b.id === Number(req.params.id));
if (!book) throw new HttpError(404, "NOT_FOUND", "Book not found");
res.json({ data: book });
});
// At the very end, after every route:
app.use((err, req, res, next) => {
const status = err.status || 500;
const code = err.code || "INTERNAL_ERROR";
const message = status === 500 ? "Something went wrong" : err.message;
if (status === 500) console.error(err); // the full details only go to the server log
res.status(status).json({ error: { code, message } });
});
class HttpError extends Errormakes a new kind of error, based on JavaScript's built-inError, that also carries astatusand acode.super(message)stores the error message as a plainErrordoes, so it can be read later aserr.message.throwstops the route and jumps to the error handler.next(err)does the same. Inside a callback (a function that is called later, for example after a file is read), you usenext(err).- Express recognises an error handler by its four parameters:
(err, req, res, next). With three, the function is taken as an ordinary middleware, and Express skips it when there's an error. app.use(...)registers a middleware for every route. Theapp.use(...)for the error handler goes after every route.err.status || 500: an error with nostatusis an unexpected bug, so it's answered500with a general message.console.error(err)writes the full details to the server log.asynchandlers (the ones that useawait): Express 5 passes an error from anawaitto the error handler by itself. In Express 4, wrap the code intry/catch(a block that catches errors) and callnext(err). More on this in the Error Handling lesson of the Node.js track.
The results for three requests. The third one reaches a reviews route (not shown here) that has a bug:
| Request | What happens | Response |
|---|---|---|
GET /books/1 |
the book is there | 200 {"data": {...}} |
GET /books/99 |
throw new HttpError(404, ...) |
404 {"error": {"code": "NOT_FOUND", "message": "Book not found"}} |
GET /books/1/reviews |
a TypeError, a bug |
500 {"error": {"code": "INTERNAL_ERROR", "message": "Something went wrong"}} |
Don't send the stack trace
A stack trace is the record of where an error happened: the error's name, files and line numbers. It is in err.stack. If the error handler answers with res.status(500).json({ error: err.stack }), the client gets something like this:
TypeError: Cannot read properties of undefined (reading 'map')
at /home/deploy/bookshop-api/src/routes/reviews.js:14:31
at Layer.handle [as handle_request] (/home/deploy/bookshop-api/node_modules/express/lib/router/layer.js:95:5)
The full stack trace goes out. The server's folder paths, file names, line numbers and the libraries it uses become a map for an attacker. The user can do nothing with them. The client only needs INTERNAL_ERROR and "Something went wrong". The details go to the server log through console.error(err), where developers look for them.
⚠️ Error handlers that get skipped, statuses that mislead
- An error handler with three parameters.
(err, req, res)withoutnextis taken as an ordinary middleware. Write all four, even ifnextis never used. - The error handler above the routes. Middleware runs in the order it was registered. An error from a route registered after the error handler never reaches it. Put
app.use((err, req, res, next) => ...)last. - An error answered 200.
res.json({ error: "..." })has status200, so in the frontend,res.okfromfetchis true (it counts as a success). Use a 4xx or 5xx status. - A client's mistake answered 500. Failed validation is
400or422. A500makes the client think the server broke, and then try again, which doesn't help. - A stack trace or SQL message to the client. Send a general message, keep the details in the log.
TL;DR: 4xx means a client-side error (fix the request), 5xx means a server-side error. 400 a broken request, 401 not recognised, 403 logged in but not permitted, 404 not there, 409 a clash with existing data, 422 breaks the rules, 500 a bug. Use one error shape on every endpoint: {"error": {"code": "NOT_FOUND", "message": "..."}}, or RFC 9457 Problem Details, the official standard for errors (type, title, status, detail, instance, with Content-Type: application/problem+json). Routes throw their errors (throw or next(err)). One error handler, a middleware with four parameters (err, req, res, next) registered last with app.use, reads err.status and answers them all. An unexpected error becomes 500 INTERNAL_ERROR "Something went wrong". The stack trace (the record of the files and lines where the error happened) only goes to the server log, never to the client.
⚡ 4xx is the client's fault, 5xx the server's
Meaning: The first digit of a status code already says who has to act. 4xx: the request needs fixing. Sent again unchanged, it usually gives the same result, except for 429 (too many requests) and 408 (the waiting time ran out). 5xx: the client did nothing wrong, and trying again later may work.
⚡ One central error handler
Write:
app.use((err, req, res, next) => {
const status = err.status || 500;
const code = err.code || "INTERNAL_ERROR";
const message = status === 500 ? "Something went wrong" : err.message;
if (status === 500) console.error(err); // the full details only go to the server log
res.status(status).json({ error: { code, message } });
});
Guess first: Express recognises an error handler (the middleware that answers every error) by its four parameters. Say an error handler is written (err, req, res), with no next. What happens when there's an error?
The error handler gets skipped. Express recognises an error handler by its four parameters, so one with three is taken as an ordinary middleware.
Meaning: Routes only throw their errors (throw or next(err)), and this error handler answers them all in one shape: {"error": {"code": ..., "message": ...}}. An error with no status is a bug, so it's answered 500 with a general message, and the details only go to the server log. Put this app.use(...) last, after every route.
⚡ Don't send the stack trace
Meaning: res.status(500).json({ error: err.stack }) sends the stack trace, the record of where the error happened: the server's folder paths, file names and line numbers. That's a map for an attacker, while a user can do nothing with it. The client only needs INTERNAL_ERROR and "Something went wrong".