Consistent error response format
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A mobile app calls three endpoints, and they fail in three different ways: JSON, plain text and a whole HTML page. The app crashes while parsing the third one and shows the user nothing useful.
One error shape for the whole API
A consistent error format means every 4xx and 5xx response has the same fields with the same meaning. The status code says what kind of failure it is; the body explains this particular failure.
Three endpoints with three error shapes, and the same three with one shape.
Example 1 · Three endpoints, three error shapes, then one
GET /api/v1/products/99 -> 404 { "error": "no product" }POST /api/v1/customers -> 400 { "msg": "Invalid", "code": 7 }POST /api/v1/orders -> 500 <html><body><h1>500 Internal Server Error</h1>...GET /api/v1/products/99 -> 404 { "type": ".../not-found", "title", "status", "detail", "instance" }
POST /api/v1/customers -> 400 { "type": ".../validation-failed", ..., "errors": [ ... ] }
POST /api/v1/orders -> 500 { "type": ".../internal-error", "title", "status", "detail", "instance" }What this code does
- Before, a client needs three parsers and still breaks on the HTML page, which a framework sends when nothing handles the error.
- After, every error has the same five fields, and only the extras (such as
errors) depend on the type. One parser handles all of them.
Without it, each endpoint invents its own: one sends {"error": "..."}, another {"msg": "...", "code": 7}, a third plain text, and a crash sends the server's HTML error page. The mobile app then needs special code per endpoint, and when one shape is missed the app shows "Something went wrong" or crashes while parsing.
Problem Details: type, title, status, detail, instance
Problem Details is a standard JSON error format for HTTP APIs, defined in RFC 9457. It has five fields: type, title, status, detail and instance.
A 404 error written as Problem Details.
Example 2 · A not-found problem
GET /api/v1/orders/999 HTTP/1.1Host: localhost:8080HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{
"type": "https://shoplite.example/problems/not-found",
"title": "Resource not found",
"status": 404,
"detail": "Order 999 was not found.",
"instance": "/api/v1/orders/999"
}What this code does
typeandtitleare the same for every not-found error in ShopLite;detailandinstancedescribe this one.- A client checks
type(or the status) to decide what to do, and may showdetailto the user. It never needs to parse the sentence.
RFC 9457 (2023) replaced RFC 7807. An RFC is a published internet standard, so many frameworks and tools already understand the format. The five fields:
type: a URI that names the kind of problem, such ashttps://shoplite.example/problems/not-found. Clients branch on it. Without one, the default isabout:blank.title: a short, fixed summary of that kind ("Resource not found"); it does not change between occurrences.status: the HTTP status code, repeated in the body.detail: a sentence about this occurrence ("Product 99 was not found."), safe to show a user.instance: which request failed; ShopLite puts the request path here.
type URI is a name, not a page the client must open. ShopLite uses the reserved .example domain in lessons; a real shop would point it at its API documentation.Validation errors: a list of field and message pairs
An extension member is an extra field added to a Problem Details body for one problem type, such as the errors list of a validation problem.
A sign-up with three broken fields, reported in one answer.
Example 3 · Validation: every broken field at once
POST /api/v1/customers HTTP/1.1Host: localhost:8080Content-Type: application/json{ "fullName": "R", "email": "ravi.at.gmail", "phone": "12345"}HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
{
"type": "https://shoplite.example/problems/validation-failed",
"title": "Validation failed",
"status": 400,
"detail": "The request has 3 invalid fields.",
"instance": "/api/v1/customers",
"errors": [
{ "field": "fullName", "message": "must be 2-100 characters" },
{ "field": "email", "message": "must be a valid e-mail address" },
{ "field": "phone", "message": "must be 10 digits starting with 6-9" }
]
}What this code does
- All three fields are wrong, and all three come back in one answer, in the order they appear in the body.
- Each
fieldmatches the JSON name the client sent, so a sign-up form can put each message right under its box.
ShopLite's validation-failed problem adds errors, a list of { "field", "message" } pairs, one per broken field. Report every broken field in one response. If the server stops at the first one, a user fixes the name, submits, learns the e-mail is wrong, and only on the third try hears about the phone. With the full list, the client can show each message under the matching form box.
Fields are named as the client sent them: fullName, a query parameter such as size, or a list position such as items[0].quantity. The out-of-stock problem below uses extension members too: productId, available and requested, so an app can say exactly how many units are left.
application/problem+json and the matching status
application/problem+json is the media type of a Problem Details body. It goes in the Content-Type header instead of plain application/json.
A 409 with extension members, and a wrong answer that hides an error inside a 200.
Example 4 · A conflict with extension members
POST /api/v1/orders HTTP/1.1Host: localhost:8080Content-Type: application/json{ "customerId": 2, "addressId": 3, "items": [ { "productId": 3, "quantity": 9 } ]}HTTP/1.1 409 Conflict
Content-Type: application/problem+json
{
"type": "https://shoplite.example/problems/out-of-stock",
"title": "Not enough stock",
"status": 409,
"detail": "Only 8 units of iPhone 15 128GB are in stock; 9 were requested.",
"instance": "/api/v1/orders",
"productId": 3,
"available": 8,
"requested": 9
}What this code does
- Ravi asks for 9 iPhones but only 8 are in stock: 409, and nothing is saved.
productId,availableandrequestedlet the app offer "Buy 8 instead?" without reading the English sentence.
Example 5 · Wrong: 200 with an error inside
HTTP/1.1 200 OKContent-Type: application/json{ "success": false, "message": "Order 14 is SHIPPED and can no longer be cancelled."}HTTP/1.1 409 Conflict
Content-Type: application/problem+json
{
"type": "https://shoplite.example/problems/invalid-state",
"title": "Invalid state change",
"status": 409,
"detail": "Order 14 is SHIPPED and can no longer be cancelled.",
"instance": "/api/v1/orders/14/cancel"
}What this code does
- The first response says OK on the status line and failure in the body. Every tool that looks only at the status counts it as a success.
- The fix uses 409,
application/problem+jsonand astatusfield that matches the status line.
A client, a logging tool or an API gateway can see from the header alone that the body is a problem. The status line and the status field must always agree, and the status must be an error code.
The worst habit is "200 with an error inside": HTTP/1.1 200 OK with {"success": false}. Caches store it as a good answer, monitoring counts it as a success, and every client must read the body to learn that the request failed.
Fix the error
Fix the response line
One line of each response is wrong. Pick the line that fixes it.
Round 1 of 3
Order 14 is already shipped, so the cancel is refused.
Error
Monitoring shows 0 failed requests today, but customers say cancelling does not work.
Never leak internals in errors
Leaking internals means an error body shows stack traces, exception class names, SQL text, table or constraint names, file paths or server versions. It must never happen.
A 500 that leaks the database, and the safe replies.
Example 6 · A leaking 500 and a safe one
HTTP/1.1 500 Internal Server ErrorContent-Type: application/json{ "error": "IntegrityError", "message": "Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email'", "sql": "INSERT INTO customers (full_name, email, phone) VALUES (?, ?, ?)", "trace": "CustomerRepository.insert line 42 <- CustomerService.register line 18 <- CustomerHandler.create line 31"}HTTP/1.1 409 Conflict
Content-Type: application/problem+json
{
"type": "https://shoplite.example/problems/already-exists",
"title": "Resource already exists",
"status": 409,
"detail": "A customer with e-mail asha.rao@example.com already exists.",
"instance": "/api/v1/customers"
}
HTTP/1.1 500 Internal Server Error
Content-Type: application/problem+json
{
"type": "https://shoplite.example/problems/internal-error",
"title": "Internal server error",
"status": 500,
"detail": "Something went wrong on our side. Please try again later.",
"instance": "/api/v1/customers"
}What this code does
- The leaking response shows the error class, the table and constraint names, the SQL and the code layout: a map of the system for an attacker. It is also the wrong code, because a duplicate e-mail is the client's problem, not a server failure.
- The fix: the expected duplicate becomes a clean 409; any truly unexpected error becomes a generic 500, and the stack trace goes only to the server log.
An error body is read by everyone who calls the API, including attackers. Each internal detail tells them how the system is built and where to aim.
The full details go to the server log, where developers can read them; the client gets a safe detail. For an unexpected failure that is a generic 500: "Something went wrong on our side." For expected failures such as a duplicate e-mail, the server turns the database error into a clean 409 with its own sentence.
Next step
Check your understanding
12 quick questions