Handling Errors

1. Structuring Error Responses

Use RFC 7807 Problem Details (application/problem+json) as the cross-language standard.

FieldRequiredPurpose
typeRecommendedURI identifying error type
titleYesShort human-readable summary
statusYesHTTP status code
detailYesSpecific explanation
instanceOptionalURI of failed request
errorsOptionalArray of field-level errors
traceIdOptionalCorrelation ID for support

2. Using Standard Error Codes

Application CodeMaps To HTTPUse
VALIDATION_FAILED422Schema/business validation
NOT_FOUND404Resource missing
UNAUTHORIZED401Missing/expired token
FORBIDDEN403Insufficient permissions
CONFLICT409State conflict
RATE_LIMITED429Quota exceeded
INTERNAL_ERROR500Unhandled exception

3. Including Field-Level Errors

Example: Field Errors Array

{
  "title": "Validation Failed",
  "status": 422,
  "errors": [
    {"field": "email",   "code": "REQUIRED",   "message": "Email is required"},
    {"field": "age",     "code": "OUT_OF_RANGE", "message": "Must be 18-120", "value": 15},
    {"field": "items[0].sku", "code": "NOT_FOUND", "message": "SKU not found"}
  ]
}

4. Providing Error Messages

AudienceMessage Type
End userFriendly, actionable, localized
DeveloperTechnical detail, machine-readable code
Logs onlyFull stack trace, internal IDs
FieldExample
type (URI)https://api.example.com/docs/errors/validation
helpUrlCustom field linking to docs/troubleshooting

6. Handling Validation Errors

StageStatusBody
Malformed JSON400Parse error position
Schema mismatch400 or 422Field paths + codes
Business rule422Rule code + explanation

7. Handling Server Errors

StatusCauseAction
500Unhandled exceptionLog fully; return generic message
502Bad upstream responseRetry or fail fast
503Service unavailableInclude Retry-After
504Upstream timeoutIncrease timeout or fail

8. Implementing Error Logging

Log FieldPurpose
traceId / requestIdCorrelation across services
userId / tenantIdAffected user/tenant
endpoint + methodIdentify failing operation
statusCode + errorCodeCategorize for alerting
stack traceServer-side only, never returned
durationPerformance correlation

9. Avoiding Sensitive Information in Errors

Warning: Never expose: stack traces, SQL queries, file paths, internal IPs, secret keys, password hashes, or PII in production error responses.
Anti-PatternRisk
Stack trace in 500 bodyReveals framework, file paths
"User not found: alice@x.com"Email enumeration
SQL error verbatimSQL injection vector hint

10. Providing Localized Error Messages

ApproachImplementation
Server-side i18nResolve via Accept-Language + resource bundles
Code + client lookupReturn code; client maps to localized text
HybridCode + default English message

11. Including Stack Traces

EnvironmentStack Trace
ProductionNever in response; log only
StagingOptional under feature flag
DevelopmentOK to include in body for debugging