intermediate
REST error response shape
Return consistent machine-readable errors with codes, messages, field details, correlation IDs, and safe diagnostics.
Consistent error bodies speed client handling, support tooling, and incident correlation. [RFC 9457 Problem Details](https://www.rfc-editor.org/rfc/rfc9457) is a solid baseline.
{
"type": "https://api.example.com/errors/validation",
"title": "Validation failed",
"status": 422,
"detail": "Email format is invalid",
"instance": "/orders/req-abc123",
"errors": [
{ "field": "email", "code": "invalid_format", "message": "Must be a valid email" }
],
"correlationId": "7c9e6679-7425-40de-944b-e07fc1f90ae7"
}
Design rules:
- Stable `type` or `code` for programmatic branching (not English prose).
- Human `title`/`detail` for logs and UI; localize client-side when possible.
- Field-level `errors[]` for forms; never leak stack traces or SQL.
- `correlationId` matches server logs and tracing (also return `X-Request-Id`).
On interviews: contrast problem+json with ad-hoc `{ error: string }`, how to map domain errors to HTTP status, and what is safe in public APIs.
Common pitfalls: changing error JSON on every release, mixing validation and auth errors, exposing internal exception names, and 200 responses with embedded failure flags.
The trade-off is rich error detail versus information disclosure — tune per audience (public vs internal).
Checklist:
- Machine-stable codes; human messages separate.
- correlationId on every error response.
- Field errors for validation; generic message for 500.
- Document error catalog in OpenAPI.