Skip to content
mentoor

Topic 3 of 5 · 4 min read

Consistent, actionable API error responses

Goal: Rewrite an inconsistent set of error responses into one shape with stable codes and correct HTTP status codes.

Every error from your API should have one shape, a status code that tells the truth and a stable machine-readable code, so a client can decide what to do without parsing prose. Generated handlers drift: one returns {"error": "bad"}, the next {"message": "..."}, a third leaks a stack trace.

Check yourself · 1 of 3

Why should an API error carry a stable type or code as well as a message?

Choose one answer

Why it matters

Client code branches on errors: retry on a timeout, show a field message on a validation failure, send the user to log in on an expired session. If the shape changes per endpoint, every client carries special cases. If the message is the only signal, a copy edit becomes a breaking change.

How to do it

  1. Use a standard shape. RFC 9457 "problem details" defines a JSON object with type (a stable URI or code), title, status, detail and instance, served as application/problem+json. You can add your own members, such as errors for field problems and request_id.
  2. Pick the right status. 400 or 422 for invalid input, 401 for missing credentials, 403 for not allowed, 404 for missing, 409 for a conflict, 429 for rate limiting with a Retry-After header, 5xx only for server faults.
  3. Keep codes stable. type: "https://api.shop.example/errors/out-of-stock" never changes. The human detail can be reworded freely.
  4. Say what to do next. "Quantity must be at most 5" beats "Invalid input".
  5. Leak nothing. No stack traces, SQL, file paths, hostnames or library names. Log those server-side under a request_id and return the id so support can find it.

Before and after

{"error": "ER_DUP_ENTRY: Duplicate entry 'ada@x.com' for key 'users.email' at /srv/app/db.js:88"}

A 500 with SQL internals. Reviewed:

{
  "type": "https://api.shop.example/errors/email-taken",
  "title": "Email already registered",
  "status": 409,
  "detail": "An account with this email already exists. Sign in or reset your password.",
  "request_id": "req_7f3a"
}

What goes wrong

  • The catch-all. A model wraps everything in catch (e) { res.status(500).json({error: e.message}) }, which turns client mistakes into 500s and leaks internals.
  • Prose as the contract. Clients match on "not found" and break when someone edits the text.
  • Account enumeration. Telling a caller that "no user with that email" exists on a login or reset route helps attackers. Return the same response either way.

Examples

Three endpoints, three shapes

{"error": "bad"}
{"message": "Not found", "ok": false}
{"errors": ["name required"]}

A client needs three parsers. Ask for one problem-details object with type, status, detail and an errors array for field issues, and one shared error-handling helper that all routes use.

A leaky 500

{"stack": "Error: connect ECONNREFUSED 10.0.3.12:5432\n at ..."}

This reveals an internal IP and database port. Return 503 with a generic detail and a request_id, and log the stack on the server.

Key points

  • Return one error shape everywhere, and RFC 9457 problem details is a ready-made standard for it.
  • Use a stable machine-readable type or code, because the human text will change and must not be the contract.
  • Status codes must tell the truth: client mistakes are 4xx, only server faults are 5xx, and 429 carries Retry-After.
  • Never return stack traces, SQL, paths or library names; log them with a request id and return the id.
  • Write each error so the caller knows what failed and what to do next.

Common mistakes

  • Returning e.message from the exception to the client.
  • Using 500 for validation or permission failures.
  • Changing the wording of an error and breaking clients that matched on it.
  • Giving every error a different shape because each route was generated separately.

Check yourself · 2 of 3

A generated handler catches every exception and returns 500 with e.message. A user sends an invalid email. What is wrong?

Choose one answer

Check yourself · 3 of 3

Which error body is the best one for a duplicate email on signup?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic