Hmm, the user is asking about designing error handling for a REST API, specifically HTTP status codes and JSON error responses. They want clear guidelines on client vs server errors and examples for common cases.
Okay, first I need to confirm the standard HTTP status ranges: 4xx for client errors, 5xx for server errors. For client errors, I should list the most relevant ones like 400, 401, 403, 404, 409, 422, 429. For server errors, generic 500 and maybe 503 for maintenance.
For the JSON body, fields like error code (machine-readable), message (human-readable), correlation ID (for tracing), and maybe details for validation. The examples need to be practical—404 for a missing resource, 400 for validation with field-level errors.
I should emphasize consistency and predictability. The correlation ID is crucial for debugging. For validation, showing which fields failed makes the API developer-friendly. Avoid exposing internal errors in 5xx responses.
Examples should be concise but complete. For 404, include a unique error code and message. For 400 validation, list each invalid field. Both must have the correlation ID.
The user might be building an API from scratch, so they need actionable patterns. No need to overcomplicate—stick to widely accepted practices.
Excellent question. Proper error handling is critical for a usable, debuggable, and professional REST API. Here’s a comprehensive guide based on industry best practices.
1. HTTP Status Code Ranges
- Client Errors (4xx): The request is malformed, invalid, or cannot be fulfilled due to the client's actions. The client can change something to retry.
- Server Errors (5xx): The server failed to fulfill a valid request due to an internal problem. The client should retry later (or not, depending on the code). The client cannot fix this.
Common Client Error Codes (4xx):
400 Bad Request: General syntax error, invalid request message, or failed validation.
401 Unauthorized: Missing or invalid authentication credentials.
403 Forbidden: Authenticated but lacking permission for the resource.
404 Not Found: The requested resource does not exist.
405 Method Not Allowed: Valid resource, but HTTP method (GET/POST/PUT/DELETE) is not supported.
409 Conflict: Request conflicts with current state (e.g., duplicate username).
422 Unprocessable Entity: (Often used for semantic validation errors where the syntax is correct but the business logic is violated. Some prefer 400 for all validation.)
429 Too Many Requests: Rate limiting has been triggered.
Common Server Error Codes (5xx):
500 Internal Server Error: A generic, catch-all error for unexpected server conditions. Never expose stack traces or internal details in production.
502 Bad Gateway / 504 Gateway Timeout: The API server/proxy had a problem communicating with an upstream service (database, microservice, etc.).
503 Service Unavailable: The server is down for maintenance or is overloaded. Clients should retry after a delay (use a Retry-After header).
2. Standard JSON Error Response Body Design
A consistent, structured JSON body allows clients to programmatically handle errors.
Recommended Fields:
error (string, required): A machine-readable, unique error code (e.g., "resource_not_found", "validation_error"). Use a namespaced/camelCase format. This is more stable than the HTTP status code string.
message (string, required): A human-readable description of the error. Should be concise and safe for display to end-users (if applicable).
status (integer, optional but recommended): The HTTP status code. Redundant but convenient for clients parsing the body alone.
correlation_id (string, highly recommended): A unique identifier (UUID) for this specific request/error. Essential for support and log tracing. The server must log this ID with the full error context.
details (array/object, optional): For structured errors like validation, provide an array of specific issues.
- For validation:
[{ "field": "email", "issue": "must be a valid email address" }, ...]
- For other complex errors: additional context objects.
Example Structure:
{
"error": "error_code_here",
"message": "Human-readable summary.",
"status": 400,
"correlation_id": "550e8400-e29b-41d4-a716-446655440000",
"details": [...]
}
3. Example Error Responses
Example 1: 404 Not Found
A user requests a non-existent blog post.
{
"error": "post_not_found",
"message": "The requested blog post with ID 'abc123' does not exist.",
"status": 404,
"correlation_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
- Why it's good: Clear machine code (
post_not_found), helpful human message including the problematic ID, correct status, and a correlation ID for support.
Example 2: 400 Bad Request due to Validation Failure
A client submits a new user with an invalid email and a missing required field.
{
"error": "validation_error",
"message": "The request contains invalid data. Please check the 'details' array.",
"status": 400,
"correlation_id": "f9e8d7c6-b5a4-3210-zyxw-0987654321fe",
"details": [
{
"field": "email",
"issue": "must be a valid email address",
"rejected_value": "not-an-email"
},
{
"field": "password",
"issue": "required field must not be empty"
}
]
}
- Why it's good: Top-level
validation_error code. The details array is explicit, pointing the developer to exact fields and reasons, including the rejected value. This is far superior to a generic "Invalid input" message.
Key Principles & Best Practices
- Be Consistent: Use the exact same JSON structure for all errors across your API.
- Log, Don't Leak: Log the full error (stack trace, internal codes) on the server with the
correlation_id. Return only safe, sanitized information to the client.
- Use Specific Error Codes: Don't just use
"error": "bad_request" for every 400. Differentiate ("invalid_json", "missing_parameter", "validation_error").
- Don't Overload
500: Have specific server-side error codes if possible (e.g., "database_connection_failed", "external_service_timeout"), but still return HTTP 500. This helps internal monitoring.
- Include
WWW-Authenticate Header: For 401 errors, this header must be present with details on how to authenticate (e.g., Bearer realm="api", error="invalid_token").
- Set Appropriate
Content-Type: Always return application/json for JSON error bodies.
- Consider API Versioning: If your error structure might change, include the API version in the response (e.g., via a header or in the body) or be exceptionally backward-compatible.
By following this pattern, you create an API that is developer-friendly, operationally observable, and robust under failure conditions. The correlation_id is arguably the single most important field for production support.