When a JSON API request fails, the response that comes back is easy to treat as an afterthought: grab whatever string is lying around, show it in a toast, move on. That habit costs real money in debugging time. A well-designed error response is a contract. The server promises to include certain members with certain meanings; the client promises to read them by name rather than by guessing at prose. When both sides hold up their end, failures become diagnosable from logs alone, without reproducing the bug.
The format that formalizes this contract is application/problem+json, defined by RFC 7807 and refined by RFC 9457. This guide walks through the contract clause by clause: what each standard member promises, how extension members fit in, how to separate the document from transport metadata, and the parsing habits that keep your client honest.
The failure mode: stringly-typed errors
Before the problem details format, most APIs improvised. Each endpoint invented its own error shape, and each one trained clients to scrape meaning out of free text. A typical offender looks like this:
{
"error": "Bad Request",
"message": "Validation failed: qty must be >= 1",
"code": 400,
"msg": "Validation failed"
}
Four fields, three of them overlapping, none of them specified anywhere. The word message sometimes carries the real explanation and sometimes a generic apology. The numeric code may duplicate the HTTP status or may be an internal error number from a database driver. Clients cope by writing fragile heuristics: check for message, fall back to error, then msg, then give up and stringify the whole object into a log line.
The deeper problem is that prose is not a stable identifier. The day a backend developer rewords "qty must be >= 1" to "quantity must be at least 1", every client that greps for the old substring breaks. Strings are for humans; contracts need names that survive rewording. That is the gap problem details fills: it gives each failure a stable type plus a predictable set of members around it, so the machine-readable part never depends on the human-readable part.
Problem details: a shared vocabulary
RFC 7807, published in 2016, defined a minimal JSON object for describing errors, along with the media type application/problem+json (and an XML variant most teams never use). RFC 9457, published in 2023, obsoleted it with small clarifications — notably acknowledging that status codes can be updated by proxies and tightening wording around content negotiation. The wire format is effectively the same, so older servers and newer clients interoperate without drama.
Three design decisions in the spec matter more than the rest. First, the document is deliberately tiny: five standard members, and that is all. Anything else is an extension. Second, the format is a profile, not a framework: a server can adopt it without buying into any particular error taxonomy. Third, the human-readable text and the machine-readable identity are separated on purpose. A client that only needs to branch on error category never has to parse a sentence to do it.
Adoption is also trivially visible. If a response carries Content-Type: application/problem+json, the body is a problem document, and the contract below applies. If it carries application/json, all bets are off — that is a plain JSON body and you are back to whatever private convention that API invented.
The five standard members, read as promises
Each member of a problem document makes a specific promise. Reading them as promises — rather than as loose suggestions — is what turns the format into a contract you can build against.
type: the identity of the failure
type is a URI that names the class of problem: insufficient-balance, invalid-draft, rate-limited. It is the single most important member, because it is the one clients should branch on. The URI does not have to resolve; the spec says it may point to human-readable documentation, but clients must not fail if it does not. When a server has nothing more specific to say, it uses the literal value about:blank, which means "the status code is the whole story." That default matters: it lets a generic client handle unknown APIs correctly by falling back to status-code behavior.
title: the one-line summary
title is a short, human-readable summary of the error class — the same phrase for every occurrence of that type. "Insufficient balance", not "Account 8842 is short by 37.60 USD." The distinction between class-level title and occurrence-level detail is a promise about stability: two responses with the same type should carry the same title, which makes titles safe to show in a UI header but unsafe to use as machine keys.
status: the server's opinion, not the truth
status mirrors the HTTP status code the server believed it was sending. The spec is explicit that it is duplicated into the body for convenience — a reader who saved the body to a file still knows the outcome — and that it is not authoritative. Intermediaries may rewrite status codes; a cached response may arrive with a body saying 410 while the transport says 200. The contract here is subtle: the body's status is informational, the transport status is operational. Retry logic, caching, and monitoring should key off the transport; diagnosis should read both and flag mismatches.
detail: the explanation of this occurrence
detail is free text specific to this failure: which account, which field, how far off the number was. This is the member most often misused, because it is tempting to treat "human-readable" as "user-safe." The spec promises only that it is oriented toward a developer reading the exchange — not that it is free of internal jargon, identifiers, or stack-adjacent information. A client that pipes detail straight into an end-user dialog is trusting the server to have curated it. Some do; many do not.
instance: where it happened
instance is a URI identifying the specific occurrence — often the path of the offending resource, sometimes an ID of the failed operation. It is a support ticket in miniature: "the transfer /transfers/tx_20913, not transfers in general." Log it verbatim. When a user reports a failure, the instance plus the type usually narrows the search to a single row in a single table.
| Member | What it promises | How a client should use it |
|---|---|---|
type | Stable URI identifying the error class; about:blank if none | Branch on it in code; never require the URI to resolve |
title | Class-level summary, identical across occurrences of a type | Display as a headline; never parse or match on it |
status | The status the server thought it sent | Informational only; trust the transport for logic |
detail | Occurrence-specific explanation for a developer | Show to developers; screen it before showing to end users |
instance | Identifier for this specific occurrence | Log verbatim; quote it in support conversations |
A minimal, well-formed document uses all five:
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
Content-Language: en
{
"type": "https://api.ledgerly.example/problems/insufficient-balance",
"title": "Insufficient balance",
"status": 422,
"detail": "Account 8842 holds 12.40 USD; this transfer needs 50.00 USD.",
"instance": "/transfers/tx_20913"
}
Extension members: the open part of the contract
Five members would be cramped for most real APIs, so the format is explicitly extensible. Anything beyond the standard five is an extension member, and the spec defines exactly one rule for them: clients must ignore members they do not recognize. That rule is what lets a server add traceId today and retryAfter next quarter without breaking any client deployed last year. It is the same forward-compatibility bargain that makes JSON APIs evolvable at all — the same principle behind treating unknown query fields as opaque, and it deserves the same discipline on the error path as on the success path.
For the API designer, extensions are where the real diagnostics live: machine-readable field-level validation errors, rate-limit windows, correlation IDs, links to documentation. For the client author, the discipline is to consume extensions deliberately, by name, after reading that API's documentation — never to build generic logic that assumes any particular extension exists. A client that crashes because errors turned out to be an object instead of an array has violated the contract just as surely as a server that renames title.
One practical middle ground: if your ecosystem shares a common client (an internal SDK, a generated client from the API's schema), it is reasonable for that client to know the API's documented extensions. What is never reasonable is a public client inventing semantics for a member it was not told about.
A worked example: validation failure
Consider a fictional writing service, Inkwell, exposed at api.inkwell.example. A client POSTs a draft with a missing title and one over-long tag. The service responds:
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json; charset=utf-8
{
"type": "https://api.inkwell.example/problems/invalid-draft",
"title": "The draft could not be saved",
"status": 422,
"detail": "Two fields failed validation. No changes were written.",
"instance": "/v2/drafts/5171",
"errors": [
{
"pointer": "/title",
"reason": "required",
"message": "A title is required before a draft can be saved."
},
{
"pointer": "/tags/2",
"reason": "too-long",
"message": "Tags are limited to 24 characters."
}
],
"requestId": "req_a41f9c",
"traceId": "4bf19f2e8c"
}
Read it as a contract and every member earns its place. The type URI says this is the invalid-draft class — a client can maintain a handler for exactly that string. The title is class-level phrasing, identical for every invalid draft; the detail is occurrence-specific and mentions the count. The instance names the exact draft that failed, and status repeats 422 for anyone reading the saved body later.
The interesting part is the errors extension. Each entry carries a pointer — a JSON Pointer referencing the offending location in the request document. Note the second one: /tags/2 points at the third element of the tags array, which is exactly how array indexing works in pointer syntax. If your tag keys could ever contain slashes or tildes, the pointer will escape them, and a client that decodes pointers naively will mislocate the field. We have covered the encoding rules in the guide on JSON Pointer escapes, including the tilde-swap that makes ~1 and ~0 stand in for slashes and tildes; the companion piece on forward-slash escaping explains when those escapes show up in keys themselves.
The requestId and traceId members are pure extensions. A generic client ignores them; Inkwell's own SDK logs them, because they join the server's log stream to the client's report. That division — generic clients stay ignorant, specific clients opt in — is the contract working as designed.
Problem details versus transport metadata
A problem document travels inside an HTTP response, and it is tempting to blur the line between the document and its envelope. Keep them separate. The status member duplicates the transport status; the transport status is what fetch, proxies, caches, and monitoring systems act on. Retry headers such as Retry-After live in the envelope, not the body. Content language lives in Content-Language, not inside the document. Authentication challenges live in WWW-Authenticate.
The same separation applies in reverse: never stuff transport facts into the body when the envelope has a standard place for them. A server that writes "retryAfterMs": 30000 into a problem document while omitting the Retry-After header forces every client — including the ones that speak plain HTTP — to parse JSON to learn what HTTP already says. We treat the header side of this division in more depth in the guide on JSON in HTTP headers.
The diagnostic habit that follows: when logging a failed request, capture the envelope (status, relevant headers) and the document (parsed members) as two separate structures, and alert on mismatches. A body claiming 500 while the transport says 502 usually means an intermediary wrote the response, and that fact changes who needs to investigate.
Never assume detail is safe to show end users. Servers routinely embed internal identifiers, SQL fragments, or upstream error text in it. Route detail to developer-facing surfaces — logs, admin views, support tools — and show users the title or your own localized message keyed off type.
Extracting and logging problem details reliably
The extraction code should encode the contract's rules explicitly: detect the media type, parse defensively, promote the document onto the error object, and never trust a single source of truth for status. Here is a fetch handler shaped that way:
async function callApi(url, options) {
const res = await fetch(url, options);
const type = res.headers.get("Content-Type") || "";
if (!res.ok && type.startsWith("application/problem+json")) {
const problem = await res.json();
const error = new Error(problem.title || "Request failed");
error.problem = problem; // the whole document
error.type = problem.type; // branch on this
error.status = problem.status ?? res.status;
error.instance = problem.instance ?? null;
throw error;
}
if (!res.ok) {
// Not a problem document: keep a bounded copy for the log,
// but never render an unvetted body to the user.
const raw = await res.text();
const error = new Error(`Request failed with status ${res.status}`);
error.rawBody = raw.slice(0, 2000);
error.contentType = type;
throw error;
}
return res.json();
}
Three choices in that handler deserve comment. The media-type check comes before parsing, so a proxy's HTML error page can never masquerade as a problem document. The ?? fallback copies the transport status into error.status when the body omits status — generous, because plenty of deployed servers omit it — while the transport status remains the value your retry logic consults. And the non-problem branch keeps a truncated raw body instead of discarding it, because the first question after an unexplained 500 is always "what did the body actually say?"
Logging should emit a flat, greppable record rather than the raw object. Flat records survive log pipelines that truncate nested objects, and they make the mismatch between body and transport visible at a glance:
function logProblem(error) {
const p = error.problem || {};
console.log(JSON.stringify({
event: "api_problem",
type: p.type ?? null,
title: p.title ?? null,
status: p.status ?? error.status ?? null,
instance: p.instance ?? null,
requestId: p.requestId ?? null,
traceId: p.traceId ?? null
}));
}
Whatever fields your APIs extend the contract with, mirror them here by name. The one thing to avoid is logging detail into a store that end users or support agents can read without screening — the callout above applies to logs as much as to screens.
Common mistakes
Assuming detail is user-safe
Covered above, but it bears repeating because it is the most frequent production incident of the five. The failure pattern is always the same: detail is friendly in every response the developer personally tested, then one day an upstream timeout produces "connection refused to 10.0.4.19:5432" in a customer-facing dialog. Treat detail as developer-scoped by default and require an explicit, reviewed decision per error type before it reaches users.
Trusting the status code alone
A 400 does not tell you which contract was violated, and two different failure classes at the same status demand different client behavior — a malformed request should be fixed by a developer, a rate-limit rejection should be retried after a delay. Status codes route the response through HTTP machinery; they are not a substitute for the error taxonomy. Branch on type, fall back to status, and never the reverse. The same skepticism applies to success codes: a 200 carrying an embedded error object is a server-side smell, but a client that checks res.ok and skips validation of the payload will ship the bug to users.
Parsing HTML error pages
When a gateway, load balancer, or the framework's default handler intercepts a request, the response body is often an HTML page — a stack trace, a branded "something went wrong" page, or a default nginx error. Clients that blindly call res.json() on every non-2xx response throw a parse error whose message contains a fragment of HTML, which is both useless and alarming in logs. Check Content-Type first, exactly as the handler above does. If the body is not JSON, record the fact, keep a bounded raw copy, and surface a generic message. The same discipline applies to responses typed application/json that are not problem documents: their shapes are private conventions, so extract nothing beyond what that API's documentation promises.
A fourth mistake is worth a sentence: treating about:blank as an error in its own right. It is the spec's way of saying "no more specific type exists", so a client seeing it should behave exactly as it would for the bare status code — not display the URI, not treat it as unknown and crash.
Test it yourself
The fastest way to internalize this contract is to inspect real responses rather than read about them. Capture a failing response from any API you work with and paste it into the JSON Inspector to see the member structure laid out — whether errors is an array or an object, which extensions the server actually sends, and whether status matches the transport code you observed. When you are evaluating two API error formats against each other, paste both documents into JSON Compare and diff them member by member; the differences you find are usually the differences your client code will need to absorb.
Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.