API errors a client can handle
Six API problem responses, an independent consumer and a tested Symfony kernel: statuses, localization, safe fields and retry limits.
An editor presses Save, and the interface receives “An error occurred.” Should they fix the title? Sign in again? Wait? Check whether the note was already created? The same red banner hides different situations and leaves the decision to someone who cannot see the server-side cause.
In the article about checking a protected origin, statuses were part of checking the network path. Here we examine a different boundary: what next action an application can choose after an API refuses a request. Returning arbitrary JSON with an error key is not enough.
Consider an executed synthetic experiment for notes: six responses, explicit machine-readable signals and a separate consumer. First, 55 literal factory and consumer cases ran; then 23 unique cases passed through the real kernel of one Symfony Demo with debug disabled. These are local request/response checks without network transport.
Status, problem type and text do different jobs
The HTTP status reports the general outcome. type identifies the specific problem. title and detail explain it to a person. We use application/problem+json as defined by RFC 9457. The client recognizes a problem by type; translating its title must not change the decision.
Our example adds a custom code extension: a short, stable alias convenient for the client's catalogue. The standard does not require it. If an API already works well with the type URI alone, duplication may be unnecessary. We keep both signals, fix their one-to-one relationship and check it. Renaming a message does not rename the code.
Here is the teaching response body with status 422 for locale en. This machine-readable example is identical in all three article editions; localized title and detail are checked in separate cases.
{
"type": "https://api.example.invalid/problems/input-invalid",
"title": "Check the input",
"status": 422,
"detail": "Correct the marked fields.",
"code": "input_invalid",
"request_id": "req_a1b2c3d4e5f6",
"errors": [
{"pointer": "/title", "code": "required", "message": "Enter a value."}
]
}
The .invalid address is an invented identifier. The client does not open it to decide what to do. In a real API, type addresses and their documentation need an owner and stable rules. An incidental URL for an exception page is unsuitable.
The body's status does not replace the actual HTTP status. RFC 9457 requires the generator to keep them consistent, but a client may encounter a contradiction, including after a response passes through an intermediary. Our client preserves the received response.status and uses a generic message on disagreement. A body containing 503 does not turn an actual 403 into permission to retry.
Six responses and six understandable situations
The catalogue starts with interface behavior. Exception class names can come later. Our teaching API adopts this agreement:
| Status | Custom code | Client decision |
|---|---|---|
| 401 | auth_required |
Offer a way to obtain valid credentials |
| 403 | operation_forbidden |
Explain that this operation is unavailable |
| 404 | note_unavailable |
Show that no note is available at the address |
| 422 | input_invalid |
Mark specific fields for correction |
| 429 | rate_limited |
Pause requests and assess retry conditions |
| 503 | service_unavailable |
Explain temporary unavailability and assess the next action |
HTTP Semantics defines 401, 403, 404, 422 and 503; RFC 6585 describes 429. The custom codes and interface decisions belong to our contract. Another product may define several problem types with the same status.
A 401 response needs WWW-Authenticate. The example has one agreed Bearer challenge. It neither issues tokens nor starts an endless credentials-refresh loop. After a 403, repeating the same operation under the same conditions is not a useful scenario either.
The 404 wording is deliberate: the client cannot conclude that the record never existed. A refusal may conceal a resource's existence. Our 422 concerns a document that is understood but contains unacceptable values; syntactically broken JSON needs another classification. Here 503 means known temporary service unavailability, rather than any caught exception.
Field errors must refer to public input
Each item in our errors carries a public field pointer and a stable validation code. The client knows only /title and /body, plus required and too_long. It uses that pair to select its own localized hint. The server's message remains an explanation for a person, not an if condition.
This is our contract extension, not a universal format for validation errors. Entity property names, internal object paths and SQL error text are not transferred. The factory accepts allowed pairs and creates the messages itself. It rejects unknown fields or codes; a single encoding call cannot turn an arbitrary internal array into a response.
Multiple violations need defined behavior too. Here the limit is ten items, duplicate pairs are rejected and order is preserved. If the form later gains nested collections, addressing them needs a separate agreement. Silently attaching an unknown path to the first field would give the wrong advice.
request_id provides a short reference for a support request. Literal fixtures use invented values; the HTTP adapter separately creates a random opaque reference on the server and does not copy a user header. The factory only validates its shape. It is neither a log URL, a user number nor permission to read another record. Linking it to protected diagnostics and storing those diagnostics are not implemented here.
The public document contains no exception trace, dependency classes or secrets. RFC 9457 specifically cautions against turning problem details into a debugging tool. Escaping an inappropriate message does not make it suitable for a public response.
Waiting and repeating are separate decisions
Retry-After conveys waiting time. It can contain seconds or an HTTP date, as the header definition explains. That hint alone says nothing about whether creating the note again is safe.
Consider a POST for which the client receives an unavailability response from an intermediary. The internal operation may already have happened. Blind repetition risks creating a second note. For non-idempotent requests, HTTP retry rules require separate knowledge about the semantics or that the original request was not applied. “Temporary error” does not provide that knowledge.
Our client permits scheduling only one automatic retry of a GET read. It requires a recognized 429 or 503 problem, an unused attempt and an acceptable timing hint. The method and attempt state come from local request context. A response field saying retryable: true cannot turn a POST into a safe read.
| Condition | Waiting time | Automatic retry in this exercise |
|---|---|---|
GET, first failure, Retry-After: 30 |
30 seconds | One may be scheduled |
| POST with the same response | 30 seconds | The operation needs a separate decision |
| GET after the attempt was used | 30 seconds | The budget is exhausted |
| GET with unknown or unsupported timing | Undetermined | Stop for further assessment |
To keep the example small, its parser accepts only a canonical positive integer from 1 to 300 seconds. An HTTP date, zero or a longer delay does not trigger automatic retry. This is a client policy limit: those values may be valid HTTP. Supporting dates would require time parsing and checking clock assumptions.
The client returns a decision; it does not sleep or send requests. A future scheduler must respect the delay, preserve the attempt limit and handle user cancellation. A timeout without a response is another situation: a received problem document cannot be invented for it. The operation's uncertain outcome must first be preserved.
A client must cope with an unfamiliar problem
Before choosing a specific action, the client checks the content type, size, JSON structure and consistency of recognized signals. An unknown type, a wrongly typed number or an incompatible code produces a generic message while retaining the HTTP status. This provides a controlled failure even when a newer server has moved ahead of the client.
Unknown extensions are ignored, as RFC 9457 specifies. Our recognized types nevertheless have a stricter local agreement: status and code are required. This is not a universal standards validator. An invalid optional request reference is simply discarded; it never becomes an address to open automatically.
The class's size limit only protects processing of an already received string. A real HTTP client must also limit network reads and resolve ambiguous headers. The example's built-in JSON decoder does not detect repeated object member names. A contract that requires their rejection needs an additional check at that boundary.
Check independent expectations
In the accompanying example, ProblemFactory creates responses and ProblemClient makes decisions. Their expectations are recorded in literal JSON fixtures. The test does not ask the factory to generate its own reference result.
All 55 scenarios ran: eight exact responses, ten rejected factory arguments and 37 consumer cases. They include a translated title, an unknown extension, conflicting statuses, HTML instead of JSON, an invalid validation path, a missing challenge, an exhausted attempt and a POST with retryable: true. Types and values are compared; JSON object key order does not matter.
In the one existing Demo, reproduce the checks with:
APP_ENV=test APP_DEBUG=0 php bin/phpunit tests/ApiProblems
The experiment ran on PHP 8.5.12 in a Symfony 8.1 Demo without adding dependencies. A separate PHPUnit adapter checks unchanged literal fixtures and invokes the 55-case harness. Kernel checks add another layer; they do not turn the local consumer into a complete HTTP client.
Return the contract through the real HTTP path
The integration extends one Symfony Demo. It returns the response through Symfony JsonResponse, preserving application/problem+json. A dedicated stateless firewall uses synthetic local credentials only. A missing or invalid Bearer produces 401 through the security entry point/failure handler; an authenticated identity without the required role gets 403 through access control.
All six catalogue statuses were checked in Ukrainian, Russian and English: 18 combinations. Real routing, MapRequestPayload, validation and exception handling complement security. Checks cover MIME, no-store, challenge, Content-Language, HTTP/body status agreement, stable type/code, localized title and the absence of private sentinel values from public responses. API Platform also documents separate error rules; this Demo uses its own bounded Symfony boundary and does not test API Platform.
Five further cases cover an invalid credential, malformed JSON, an arbitrary programming exception, a rejected HTTP method and successful reads/input with fresh references. Only the teaching input route maps malformed JSON to a local 422 policy with /body/required: replace the unusable document. This is not a universal HTTP classification. Real routing 405 preserves its status and Allow; an unexpected programming exception produces a safe generic 500 rather than an invented 503.
At the 429/503 boundary, an integer Retry-After from the framework exception needed normalization to a string before bounded parsing. The consumer then applies the same decision policy to actual responses: GET may propose one retry, while a spent budget or POST permits only manual review. A scheduler, clock, actual waiting, repeated network request and HTTP-date parser are not implemented. Public-response checks also do not establish redaction in every log or third-party trace.