Error Handling — API

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…

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:

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" } }

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"
}

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 } });
});

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

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".

What you will learn