API Error Response Format
A standardized structure for error responses that includes machine-readable error codes, human-readable messages, and field-level details.
Description
A consistent API error response format enables clients to programmatically handle different error conditions without parsing error message strings. The RFC 9457 (Problem Details for HTTP APIs) standard defines a structure with type (a URI identifying the error type), title (a short human-readable summary), status (the HTTP status code), detail (a human-readable explanation specific to this occurrence), and instance (a URI identifying this specific occurrence). Many APIs adopt a similar but simpler format: { error: { code: 'INVOICE_NOT_FOUND', message: '...', details: [...] } }.
For validation errors, the format should include field-level details so clients can display errors next to specific form fields: { error: { code: 'VALIDATION_ERROR', message: 'Invalid request', details: [{ field: 'email', code: 'invalid_format', message: 'Must be a valid email address' }] } }. The error code should be a stable, machine-readable string (not a number that changes meaning between versions) that clients can use in switch statements or error-handling maps.
Error responses should be consistent across all endpoints and error types. A client interacting with the API should never have to guess the shape of an error response. Internal server errors (500) should return the same structure but with generic messages that don't leak implementation details (stack traces, SQL errors, internal service names). A unique error instance ID (tied to the request ID) allows support teams to correlate user-reported errors with server-side logs.
Prompt Snippet
Adopt RFC 9457 (Problem Details) as the error response format: { type: 'https://api.example.com/errors/validation-failed', title: 'Validation Failed', status: 422, detail: 'The invoice due_date must be in the future', instance: '/errors/req_abc123', errors: [{ field: 'due_date', code: 'date_in_past', message: '...' }] }. Set Content-Type to application/problem+json on all error responses. Map every application error to a stable, documented error code enum. Redact internal details (stack traces, SQL) from 5xx responses but include the request_id for support correlation.Tags
Related Terms
HTTP Status Code Selection
Choosing semantically correct HTTP status codes so clients can programmatically handle success, client errors, and server errors.
Response Envelope Pattern
Wrapping API responses in a consistent top-level structure with data, metadata, and error fields for predictable client parsing.
Request Validation (Zod/Joi)
Runtime validation of incoming API request bodies, query parameters, and path parameters using schema libraries like Zod or Joi.