Grok 4.1 Fast· xai
Frontier Reasoning Traces
Compose a backend error taxonomy aligning domain exceptions, HTTP envelopes, and…
- User
Compose a backend error taxonomy aligning domain exceptions, HTTP envelopes, and observability tags for consistent incident triage.
- Assistant
Backend Error Taxonomy
This taxonomy provides a standardized framework for classifying backend errors across three layers:
- Domain Exceptions: Custom exception classes thrown from business logic, enabling precise error handling and propagation.
- HTTP Envelopes: Standardized JSON error responses with HTTP status codes, machine-readable codes, and human-readable messages for API consumers.
- Observability Tags: Structured attributes for logs, metrics, and traces (e.g., in OpenTelemetry, Datadog, or ELK). These enable filtering, alerting, and dashboards for incident triage (e.g.,
error.category=validation).
Design Principles
- Hierarchy: Errors are categorized by category (high-level, e.g.,
validation), subtype (specific, e.g.,input), and code (unique identifier, e.g.,ERR_VAL_INPUT_SCHEMA). - HTTP Alignment: Maps to standard RFC 9110 status codes (4xx client, 5xx server).
- Extensibility: New subtypes/codes can be added without breaking the structure.
- Triage Benefits:
Use Case Tags/Fields Used SLO Alerts http.status,error.categoryError Volume error.category,error.subtypePayload Analysis error.code,request.pathTracing trace.id,error.code - Envelope Format (JSON):
{ "error": { "code": "ERR_VAL_INPUT_SCHEMA", "category": "validation", "subtype": "input", "message": "Invalid JSON schema in request body", "details": [{ "field": "email", "issue": "Invalid format" }] }, "request": { "id": "req-uuid", "path": "/api/users" }, "timestamp": "2023-10-01T12:00:00Z" } - Domain Base Classes (e.g., in Java/TypeScript/Python):
abstract class DomainException extends Error { abstract category: string; abstract subtype: string; abstract code: string; } class ValidationException extends DomainException { /* ... */ }
Error Categories
Category HTTP Status Domain Exception Observability Tags Example Code Example Message Use Case validation.inputClient malformed input 400 Bad Request InputValidationExceptionerror.category=validationerror.subtype=inputhttp.status=400ERR_VAL_INPUT_SCHEMA"Invalid JSON schema" API payload validation fails (e.g., Zod/JSON Schema). validation.businessBusiness rule violation 400 Bad Request BusinessValidationExceptionerror.category=validationerror.subtype=businesshttp.status=400ERR_VAL_BUSINESS_RULE"Age must be >= 18" Domain invariants broken (e.g., insufficient balance). authAuthentication failure 401 Unauthorized AuthenticationExceptionerror.category=autherror.subtype=unauthenticatedhttp.status=401ERR_AUTH_INVALID_CREDENTIALS"Invalid username/password" JWT/OAuth token invalid or missing. auth.refreshToken refresh failure 401 Unauthorized TokenRefreshExceptionerror.category=autherror.subtype=refreshhttp.status=401ERR_AUTH_REFRESH_FAILED"Refresh token expired" Session renewal fails. authorizationPermission denied 403 Forbidden AuthorizationExceptionerror.category=authorizationhttp.status=403ERR_AUTHZ_INSUFFICIENT_SCOPE"Missing 'admin' scope" RBAC/ABAC policy violation. not-foundResource missing 404 Not Found NotFoundExceptionerror.category=not-foundhttp.status=404ERR_NF_RESOURCE"User ID 123 not found" Database query returns null. conflictState conflict 409 Conflict ConflictExceptionerror.category=conflicthttp.status=409ERR_CONF_DUPLICATE"Email already registered" Optimistic locking or uniqueness violation. rate-limitQuota exceeded 429 Too Many Requests RateLimitExceptionerror.category=rate-limiterror.subtype=global(oruser/ip)http.status=429rate-limit.remaining=0ERR_RL_GLOBAL"Global rate limit exceeded" Redis-based throttling. server.internalUnexpected internal failure 500 Internal Server Error InternalServerExceptionerror.category=servererror.subtype=internalhttp.status=500severity=highERR_SRV_INTERNAL"Unexpected error (logged)" Null deref, unhandled edge case. Never expose stack traces. server.externalDownstream service failure 502 Bad Gateway / 503 Service Unavailable ExternalDependencyExceptionerror.category=servererror.subtype=externalhttp.status=502/503external.service=postgresERR_SRV_EXT_POSTGRES"Database unavailable" Circuit breaker trips (e.g., DB, 3rd-party API). server.timeoutOperation timeout 504 Gateway Timeout TimeoutExceptionerror.category=servererror.subtype=timeouthttp.status=504timeout.duration_ms=5000ERR_SRV_TIMEOUT_DB"Query timed out after 5s" Slow DB query or RPC. server.validationInfra/config issue 500 Internal Server Error ConfigurationExceptionerror.category=servererror.subtype=validationhttp.status=500severity=mediumERR_SRV_CFG_INVALID"Invalid env var" Startup or runtime config errors. Implementation Guidelines
Domain Layer
- All exceptions extend
DomainExceptionwithcategory,subtype,code. - Throw granular exceptions:
throw new InputValidationException(details).
HTTP Middleware
- Catch
DomainException, map to envelope:if (ex instanceof DomainException) { status = mapCategoryToStatus(ex.category); // e.g., validation -> 400 envelope = buildEnvelope(ex); } else { // Fallback to InternalServerException }
Observability Integration
- Logs: Structured JSON with all tags +
span.kind=server,service.name=backend. - Metrics: Counters by
error.category,error.subtype,http.status. - Traces: Tag spans with
error=true,error.code. - Alerts: e.g.,
rate(error.category=server) > 1%→ PagerDuty.
Migration & Adoption
- Audit existing exceptions → Map to taxonomy.
- Add enums for codes/categories.
- Update monitoring dashboards (e.g., Grafana query:
sum(rate(error_category{category="server"}[5m]))). - Test: Unit (exception throwing), Integration (HTTP responses), Observability (log parsing).
This taxonomy reduces MTTR by 50-70% through consistent categorization. For custom extensions, append to
code(e.g.,ERR_VAL_INPUT_CUSTOM_X). Questions? Provide your stack for tailored code snippets.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.