Why Consistency Matters
Nothing frustrates API consumers more than inconsistent error responses. One endpoint returns {"error": "not found"}, another returns {"message": "Not Found", "code": 404}, and a third returns plain text. Pick a format and stick to it.
The Basic Error Object
A good error response includes:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request body contains invalid fields.",
"details": [
{"field": "email", "message": "Must be a valid email address."},
{"field": "age", "message": "Must be a positive integer."}
]
}
}
RFC 7807 Problem Details
RFC 7807 defines a standard format for error responses:
{
"type": "https://api.example.com/errors/validation",
"title": "Validation Error",
"status": 422,
"detail": "The email field is not a valid email address.",
"instance": "/api/users/42"
}
The type field is a URI that links to documentation about the error type. This is the format recommended by the IETF and used by many modern APIs.
Matching Status Codes to Errors
| Scenario | Status Code | Error Code |
|---|---|---|
| Missing required field | 400 | MISSING_FIELD |
| Invalid field value | 422 | VALIDATION_ERROR |
| Resource not found | 404 | NOT_FOUND |
| Authentication required | 401 | UNAUTHORIZED |
| Insufficient permissions | 403 | FORBIDDEN |
| Rate limit exceeded | 429 | RATE_LIMIT_EXCEEDED |
| Internal failure | 500 | INTERNAL_ERROR |
Validation Errors
For validation errors, return all errors at once, not just the first one:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Multiple fields failed validation.",
"fields": {
"email": ["Invalid format.", "Already taken."],
"password": ["Must be at least 8 characters."]
}
}
}
Anti-Patterns
- 200 OK with an error body — Use proper HTTP status codes
- Leaking stack traces — Never expose server internals in production
- Generic messages — 'Something went wrong' helps nobody
- Inconsistent field names — Pick
messageormsgand stick with it - Missing error codes — Numeric/string codes are machine-readable, messages are not
Best Practice
Adopt RFC 7807 or define your own consistent schema. Document it. Return the same structure for every error. Include an error code clients can switch on, a human-readable message, and field-level details for validation errors.