Skip to content
TheChatArchiveThe Chat Archive
Grok 4.1 Fast· xaiHugging Face Frontier Reasoning Traces

Compose a backend error taxonomy aligning domain exceptions, HTTP envelopes, and…

  1. User

    Compose a backend error taxonomy aligning domain exceptions, HTTP envelopes, and observability tags for consistent incident triage.

  2. 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 CaseTags/Fields Used
      SLO Alertshttp.status, error.category
      Error Volumeerror.category, error.subtype
      Payload Analysiserror.code, request.path
      Tracingtrace.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

    CategoryHTTP StatusDomain ExceptionObservability TagsExample CodeExample MessageUse Case
    validation.inputClient malformed input400 Bad RequestInputValidationExceptionerror.category=validationerror.subtype=inputhttp.status=400ERR_VAL_INPUT_SCHEMA"Invalid JSON schema"API payload validation fails (e.g., Zod/JSON Schema).
    validation.businessBusiness rule violation400 Bad RequestBusinessValidationExceptionerror.category=validationerror.subtype=businesshttp.status=400ERR_VAL_BUSINESS_RULE"Age must be >= 18"Domain invariants broken (e.g., insufficient balance).
    authAuthentication failure401 UnauthorizedAuthenticationExceptionerror.category=autherror.subtype=unauthenticatedhttp.status=401ERR_AUTH_INVALID_CREDENTIALS"Invalid username/password"JWT/OAuth token invalid or missing.
    auth.refreshToken refresh failure401 UnauthorizedTokenRefreshExceptionerror.category=autherror.subtype=refreshhttp.status=401ERR_AUTH_REFRESH_FAILED"Refresh token expired"Session renewal fails.
    authorizationPermission denied403 ForbiddenAuthorizationExceptionerror.category=authorizationhttp.status=403ERR_AUTHZ_INSUFFICIENT_SCOPE"Missing 'admin' scope"RBAC/ABAC policy violation.
    not-foundResource missing404 Not FoundNotFoundExceptionerror.category=not-foundhttp.status=404ERR_NF_RESOURCE"User ID 123 not found"Database query returns null.
    conflictState conflict409 ConflictConflictExceptionerror.category=conflicthttp.status=409ERR_CONF_DUPLICATE"Email already registered"Optimistic locking or uniqueness violation.
    rate-limitQuota exceeded429 Too Many RequestsRateLimitExceptionerror.category=rate-limiterror.subtype=global (or user/ip)http.status=429rate-limit.remaining=0ERR_RL_GLOBAL"Global rate limit exceeded"Redis-based throttling.
    server.internalUnexpected internal failure500 Internal Server ErrorInternalServerExceptionerror.category=servererror.subtype=internalhttp.status=500severity=highERR_SRV_INTERNAL"Unexpected error (logged)"Null deref, unhandled edge case. Never expose stack traces.
    server.externalDownstream service failure502 Bad Gateway / 503 Service UnavailableExternalDependencyExceptionerror.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 timeout504 Gateway TimeoutTimeoutExceptionerror.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 issue500 Internal Server ErrorConfigurationExceptionerror.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 DomainException with category, 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

    1. Audit existing exceptions → Map to taxonomy.
    2. Add enums for codes/categories.
    3. Update monitoring dashboards (e.g., Grafana query: sum(rate(error_category{category="server"}[5m]))).
    4. 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.