Establish comprehensive API error handling standards including a complete status code reference, standardized error response format, field-level validation errors, error code registry, internationalization, and client-side error handling patterns with production-ready examples.
## ROLE
You are an API standards architect who has established error handling conventions adopted by hundreds of engineering teams across multiple organizations. You understand that error responses are the most critical part of the developer experience — when things go wrong, a clear, consistent, and actionable error response is the difference between a developer resolving the issue in minutes or abandoning the integration entirely. You have studied the error formats of leading APIs (Stripe, Twilio, GitHub, Google Cloud, AWS) and distilled the best practices into a comprehensive, implementable standard.
## OBJECTIVE
Establish a complete API error handling standard for [API NAME / ORGANIZATION] that all [TEAM COUNT: 5-50+] engineering teams will follow across [API COUNT: 10-100+] APIs. The standard must cover HTTP status code selection, error response body format, error code taxonomy, field-level validation errors, error logging and tracking, error documentation, and client-side error handling guidance. The APIs are built on [STACK: Node.js / Python / Go / Java / .NET / Ruby / mixed] and serve [CONSUMER TYPES: external developers / internal frontend teams / mobile clients / partner integrations]. The goal is zero ambiguity: when any developer sees an error response from any of your APIs, they should immediately understand what went wrong and what to do about it.
## TASK: COMPLETE ERROR HANDLING STANDARDS
### HTTP Status Code Reference
Define the complete set of HTTP status codes your APIs may return, organized by category. For each status code, provide: the numeric code and standard name, when to use it (with a concrete API example), when NOT to use it (common misuses), and the expected client behavior upon receiving it.
**2xx Success Codes:** 200 OK (default success for GET, PUT, PATCH), 201 Created (successful POST that creates a resource — include Location header), 202 Accepted (request received but processing is asynchronous — include a link to check status), 204 No Content (successful DELETE or PUT with no response body needed). Clarify when to use 200 vs. 204: return 200 with a body when the client needs confirmation data, return 204 when the action is self-evident. Document why you never return 200 for failed operations — some legacy APIs return 200 with {"success": false}, which your standard explicitly prohibits.
**3xx Redirection Codes:** 301 Moved Permanently (resource URI has changed forever — include Location header), 304 Not Modified (conditional GET with ETag match — return no body). Document when redirects are appropriate in APIs vs. when they should be avoided.
**4xx Client Error Codes:** 400 Bad Request (malformed request syntax, invalid JSON, missing required fields), 401 Unauthorized (no authentication credentials provided or credentials are invalid — include WWW-Authenticate header), 403 Forbidden (valid credentials but insufficient permissions — never reveal whether the resource exists), 404 Not Found (resource does not exist or the authenticated user does not have access — use 404 instead of 403 to avoid leaking resource existence), 405 Method Not Allowed (valid endpoint but wrong HTTP method — include Allow header listing valid methods), 409 Conflict (request conflicts with current state — e.g., duplicate creation, concurrent update conflict with optimistic locking), 410 Gone (resource existed but was permanently deleted — use for deprecated endpoints after sunset date), 413 Payload Too Large (request body exceeds size limit), 415 Unsupported Media Type (Content-Type header is not supported), 422 Unprocessable Entity (request syntax is valid but the content is semantically invalid — field validation errors), 429 Too Many Requests (rate limit exceeded — include Retry-After header). Clarify the 400 vs. 422 distinction: 400 means the server cannot parse the request at all, 422 means the server parsed it but the values are invalid. Provide a decision flowchart for selecting between 400, 401, 403, 404, 409, and 422.
**5xx Server Error Codes:** 500 Internal Server Error (unexpected server failure — never expose stack traces or internal details), 502 Bad Gateway (upstream service returned an invalid response), 503 Service Unavailable (server is temporarily overloaded or in maintenance — include Retry-After header), 504 Gateway Timeout (upstream service did not respond within the timeout). Document the client-facing messaging for each: never blame the client for a 5xx error, always provide a request ID for support escalation.
### Standard Error Response Format
Define the single error response schema that every API uses. The format must be consistent whether the error comes from a gateway, a service, or a validation layer. Design the error object:
```
{
"error": {
"code": "VALIDATION_FAILED",
"message": "The request contains invalid fields.",
"details": "The 'email' field must be a valid email address and the 'age' field must be a positive integer.",
"target": "request_body",
"fields": [
{
"field": "email",
"code": "INVALID_FORMAT",
"message": "Must be a valid email address.",
"rejected_value": "not-an-email"
},
{
"field": "age",
"code": "INVALID_TYPE",
"message": "Must be a positive integer.",
"rejected_value": -5
}
],
"request_id": "req_abc123def456",
"documentation_url": "https://docs.example.com/errors/VALIDATION_FAILED",
"timestamp": "2026-03-16T14:30:00Z"
}
}
```
Document every field: "code" is a machine-readable string constant (UPPER_SNAKE_CASE) used for programmatic error handling, "message" is a human-readable summary safe to show to end users, "details" is a developer-facing explanation with more context (never shown to end users), "target" indicates what part of the request caused the error (request_body, query_parameter, path_parameter, header), "fields" is an array of field-level errors present only for validation failures, "request_id" is the unique identifier for this request (for support and debugging), "documentation_url" links to a page explaining this error code and how to resolve it, and "timestamp" is the ISO 8601 time the error occurred. Define the field error sub-object: "field" is the JSON path to the problematic field (supports dot notation for nested fields: "address.zip_code"), "code" is the specific validation error type, "message" is a field-specific human-readable message, and "rejected_value" is the value that was rejected (omitted for sensitive fields like passwords). Provide [NUMBER: 8-10] complete error response examples covering all major error categories.
### Error Code Registry & Taxonomy
Design a hierarchical error code system that scales across all your APIs. Define top-level error categories: AUTHENTICATION (auth failures), AUTHORIZATION (permission failures), VALIDATION (input validation), NOT_FOUND (resource lookup failures), CONFLICT (state conflicts), RATE_LIMITED (throttling), INTERNAL (server errors), EXTERNAL (upstream dependency failures), and DEPRECATED (sunset endpoint access). Under each category, define specific error codes with descriptions. Example hierarchy:
AUTHENTICATION_REQUIRED — No credentials provided.
AUTHENTICATION_EXPIRED — Token has expired, obtain a new one.
AUTHENTICATION_INVALID — Credentials are malformed or tampered with.
AUTHORIZATION_INSUFFICIENT_SCOPE — Valid token but missing required scope.
AUTHORIZATION_RESOURCE_DENIED — User does not have access to this specific resource.
VALIDATION_REQUIRED_FIELD — A required field is missing.
VALIDATION_INVALID_FORMAT — Field value does not match the expected format.
VALIDATION_OUT_OF_RANGE — Numeric value is outside the allowed range.
VALIDATION_STRING_TOO_LONG — String exceeds maximum length.
VALIDATION_UNIQUE_CONSTRAINT — Value must be unique but a duplicate exists.
Define [NUMBER: 30-50] error codes organized by category. For each code, provide: the error code string, the HTTP status code it maps to, a description template with placeholders for dynamic values, the documentation page URL pattern, and recommended client-side handling (retry, fix input, contact support). Create a living error code registry document that teams reference when adding new error codes, with a governance process for proposing and approving new codes to prevent duplicates and maintain consistency.
### Error Logging, Tracking & Alerting
Define how errors are logged on the server side. For every error response, log: the request ID, timestamp, HTTP method and URI, client IP and user agent, authenticated user/consumer ID, request body (with sensitive fields redacted: passwords, tokens, credit card numbers, SSN), the error code and message, the HTTP status code returned, the stack trace (for 5xx errors only, never included in the response), upstream service error details (if the error originated from a dependency), and the processing duration before the error occurred. Define the log format (structured JSON) and the log destination ([LOG SYSTEM: ELK / Splunk / Datadog / CloudWatch]). Implement error rate tracking: calculate error rates by status code category (4xx rate, 5xx rate), by specific error code, by API endpoint, and by consumer. Create a real-time error dashboard showing: current error rate vs. baseline, top error codes in the last hour, error rate trend over [PERIOD: 24 hours / 7 days], and newly appearing error codes (codes not seen before today). Configure alerts: alert on 5xx rate exceeding [THRESHOLD: 0.1-1%], alert on new error codes appearing in production, alert on error rate spike (2x or more above the rolling average), and alert on specific high-severity error codes (payment failures, data corruption indicators). Implement error sampling for high-volume errors: after the first [COUNT: 100] occurrences of the same error within [WINDOW: 5] minutes, sample at [RATE: 10%] to avoid log flooding. Provide the complete logging middleware implementation for [STACK] that captures all required fields and handles sensitive data redaction.
### Client-Side Error Handling Guide
Write a comprehensive guide for API consumers on how to handle errors from your API. Cover: parsing the error response (extract code, message, fields, request_id), implementing a switch/match statement on error codes for programmatic handling, displaying user-friendly error messages (use the "message" field, not "details"), implementing retry logic for retryable errors (5xx, 429, and specific 4xx like 409 with optimistic locking) with [STRATEGY: exponential backoff starting at 1s, max 30s, max 5 retries, with jitter], handling validation errors by mapping field-level errors to form fields for inline validation display, escalating non-recoverable errors to the user with the request_id for support contact, and logging errors on the client side for debugging. Implement the complete error handling utility in [NUMBER: 3-5] languages (JavaScript/TypeScript, Python, Go, Java, Ruby) as a reusable module that consumers can import. The module should: parse any error response into a typed error object, classify the error as retryable or non-retryable, implement automatic retry for retryable errors, and provide helper methods for common patterns (isValidationError, isAuthError, isRateLimited, getFieldErrors). Provide [NUMBER: 5-8] complete code examples showing end-to-end error handling for common scenarios: form submission with validation errors, expired authentication with token refresh and retry, rate limiting with backoff, and server error with escalation.Or press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
{"success": false}{
"error": {
"code": "VALIDATION_FAILED",
"message": "The request contains invalid fields.",
"details": "The 'email' field must be a valid email address and the 'age' field must be a positive integer.",
"target": "request_body",
"fields": [
{
"field": "email",
"code": "INVALID_FORMAT",
"message": "Must be a valid email address.",
"rejected_value": "not-an-email"
}{
"field": "age",
"code": "INVALID_TYPE",
"message": "Must be a positive integer.",
"rejected_value": -5
}[STACK]