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?
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
- Use a standard shape. RFC 9457 "problem details" defines a JSON object with
type(a stable URI or code),title,status,detailandinstance, served asapplication/problem+json. You can add your own members, such aserrorsfor field problems andrequest_id. - Pick the right status.
400or422for invalid input,401for missing credentials,403for not allowed,404for missing,409for a conflict,429for rate limiting with aRetry-Afterheader,5xxonly for server faults. - Keep codes stable.
type: "https://api.shop.example/errors/out-of-stock"never changes. The humandetailcan be reworded freely. - Say what to do next. "Quantity must be at most 5" beats "Invalid input".
- Leak nothing. No stack traces, SQL, file paths, hostnames or library names. Log those server-side under a
request_idand 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?
Check yourself · 3 of 3
Which error body is the best one for a duplicate email on signup?
Practice items, not counted towards your mastery.
Start here
- Google API Improvement Proposals (AIP) (opens in a new tab)DocsFree
A large, consistent rulebook for resource naming, standard methods, pagination, errors and compatibility.
- RFC 9457: Problem Details for HTTP APIs (opens in a new tab)StandardFree
The standard JSON error shape with type, title, status, detail and instance members.
- Idempotent requests (Stripe API reference) (opens in a new tab)DocsFree
A widely copied idempotency-key design: key reuse, parameter mismatch and key expiry.
More for this topic
- RFC 9110: HTTP Semantics (opens in a new tab)StandardFree
Defines safe and idempotent methods and what each status code means.