1. Understand the Goal: The user wants a "backend error taxonomy." This isn't just a list of HTTP status codes. It needs to align three distinct layers:
* Domain Exceptions: The actual programming language exceptions (e.g., in Java/Python/Go) representing business logic failures.
* HTTP Envelopes: The JSON structure returned to the client, including status codes, error codes, and messages.
* Observability Tags: Metadata attached to logs, metrics, and traces (OpenTelemetry/OTEL) to help SREs and developers debug incidents.
The purpose is "consistent incident triage," meaning the taxonomy should make it easy to figure out *what* went wrong, *where*, and *why* without digging through raw code immediately.
2. Deconstruct the Layers:
* **Layer 1: The "Why" (Domain Exceptions).**
* Need a hierarchy.
* Top level: `DomainException` (abstract).
* Categories: `ClientError` (4xx), `ServerError` (5xx).
* Specifics: `ResourceNotFound`, `ValidationFailed`, `Conflict`, `Unauthorized`, `ExternalServiceFailure`, `InvariantViolation`.
* **Layer 2: The "What" (HTTP Envelope).**
* Standardized JSON response. RFC 7807 (Problem Details) is the industry standard. I should adopt or slightly adapt this.
* Fields: `type` (URI), `title`, `status`, `detail`, `trace_id` (crucial for triage), `code` (internal specific error code).
* **Layer 3: The "How to find it" (Observability).**
* Semantic conventions are key here (OpenTelemetry).
* Attributes: `error.type`, `error.code`, `http.response.status_code`, `service.namespace`, `user.id` (if auth error).
3. Develop the Taxonomy Strategy:
* *Naming Convention:* Codes should be hierarchical (e.g., `USR_001`, `SYS_001` or `auth.unauthorized`, `resource.not_found`). Let's go with a structured string approach (e.g., `domain.subdomain.error_name`) as it's more readable than integers.
* *Severity/Priority:* Some errors are noise (4xx), some are critical (5xx). This needs to be reflected in logs.
4. Drafting the Content - Section by Section:
* **Introduction:** Briefly explain the philosophy (Translation layer from Code -> HTTP -> O11y).
* **The "Problem Detail" Standard (The Envelope):** Define the JSON structure.
* `type`: Link to docs.
* `code`: Machine-readable enum (e.g., `payment.card_declined`).
* `status`: HTTP status.
* **The Exception Hierarchy (The Domain):**
* Group by functional areas.
* *Group 1: Request Integrity (4xx).* Validation, Parsing.
* *Group 2: Resource State (4xx).* NotFound, Conflict, Gone.
* *Group 3: Auth/Security (4xx).* Unauthenticated, Forbidden.
* *Group 4: System/External (5xx).* Upstream failures, Timeouts, Circuit Breakers.
* **The Observability Mapping (The Triage):**
* This is the most important part for the "incident triage" requirement.
* Define attributes: `error.group_id` (fingerprints the error for alerting), `error.stack_trace` (debug), `error.is_user_triggered` (ignore for alerting).
* **Incident Triage Playbook:** How does an on-call engineer actually *use* this?
* *Scenario:* Alert fires.
* *Step 1:* Look at `error.group_id`.
* *Step 2:* Check HTTP status. Is it a user error or system error?
* *Step 3:* Check `error.category`.
5. Refining the Taxonomy (Self-Correction during drafting):
* Critique: Initially, I might just list HTTP codes.
* Correction: No, the prompt asks for domain exceptions. I need to show how a PaymentGatewayTimeout maps to a 502 and how that maps to OTEL tags.
* Formatting: Use a clear table or list format. Markdown tables are good for the mapping.
-
Final Polish:
- Add a section on Implementation (e.g., a centralized Exception Handler/Interceptor).
- Ensure the distinction between "Leakage" (don't expose stack traces to users) and "Visibility" (full stack traces in logs) is clear.
-
Constructing the Response: (This aligns with the generated output structure).
- Architecture: Centralized Error Handler.
- The Specification: The JSON schema.
- The Taxonomy Table: The core mapping of Domain -> HTTP -> O11y.
- Observability Strategy: Semantic conventions.
- Triage Guide: Operationalizing the taxonomy.
-
Review against constraints:
- Backend error taxonomy? Yes.
- Align domain exceptions? Yes.
- HTTP envelopes? Yes.
- Observability tags? Yes.
- Incident triage focus? Yes.
(Self-Correction during specific error definition):
Make sure to distinguish between NOT_FOUND (generic 404) and specific domain errors like USER_NOT_FOUND vs ORDER_NOT_FOUND. The HTTP status is the same, but the code and tags differ. I will group them by "Error Families".
Let's stick to OpenTelemetry semantic conventions where possible (e.g., http.response.status_code, error.type).
Let's create the "Error Families":
- Validation & Input
- Resource State & Lifecycle
- Authentication & Authorization
- External Dependencies
- Internal Logic/Invariants
This looks solid. Proceeding to generate output.
This taxonomy establishes a standardized "Contract of Failure" across your stack. It maps a specific Domain Exception (Code) to an HTTP Response (API Contract) and OpenTelemetry/Logging Tags (Observability).
This alignment ensures that when an alert fires based on a metric tag, the on-call engineer knows exactly what HTTP status the client saw and what exception class triggered it in the code.
1. Architectural Flow
To make this taxonomy effective, the backend must implement a Centralized Exception Handler (middleware) that acts as the translation layer.
- Code Layer: Throws
DomainException (e.g., InsufficientFundsException).
- Handler Layer: Catches exception, looks up mapping.
- HTTP Layer: Returns standardized JSON Envelope + Status Code.
- Observability Layer: Emits Metrics/Logs with standardized Tags.
2. The Error Specification (The Envelope)
We use a strict RFC 7807-inspired "Problem Detail" envelope to ensure the frontend can parse errors generically.
{
"type": "https://service.io/errors/insufficient-funds",
"code": "INSUFFICIENT_FUNDS",
"status": 409,
"title": "Payment Failed",
"detail": "The wallet balance is lower than the requested amount.",
"trace_id": "a1b2c3d4e5f6",
"context": {
"wallet_id": "usr_123",
"required": 100.00
}
}
3. The Taxonomy Matrix
This table defines the mapping for incident triage.
| Family | Domain Exception (Class) | HTTP Status | Error Code (Machine) | Obs Tags (error.*) | Severity |
|---|
| Validation | ValidationException | 400 Bad Request | VALIDATION_ERROR | error.type="validation" | INFO |
| Validation | MalformedJsonException | 400 Bad Request | MALFORMED_BODY | error.type="parsing" | INFO |
| Auth | InvalidTokenException | 401 Unauthorized | AUTH_TOKEN_INVALID | error.type="auth" | WARN |
| Auth | PermissionDeniedException | 403 Forbidden | FORBIDDEN | error.type="auth" | WARN |
| Lookup | EntityNotFoundException | 404 Not Found | NOT_FOUND | error.type="routing" | INFO |
| Conflict | DuplicateEntryException | 409 Conflict | CONFLICT_DUPLICATE | error.type="conflict" | INFO |
| Conflict | StateConflictException |
4. Observability Schema (OpenTelemetry)
For consistent triage, your logging and metrics pipeline must extract specific attributes from the exception before discarding the stack trace (for high-cardinality alerting).
The Standard Tags:
Every error log must contain these fields:
error.type: (Enum) validation, auth, conflict, logic, external, infra.
error.code: (String) The machine code from the envelope (e.g., UPSTREAM_TIMEOUT).
http.status_code: (Int) The returned status.
error.is_user_fault: (Bool) true for 4xx, false for 5xx. Crucial for SLA calculations.
Metrics Emission:
When an exception occurs, increment a counter metric:
api.errors.count{service="payment", error.type="external", error.code="UPSTREAM_TIMEOUT"}
5. Triage Guide (The "Playbook")
This taxonomy allows you to route incidents based on the error.type tag rather than reading logs blindly.
Scenario A: "The Silent 4xx" (User Fault)
- Tags:
error.is_user_fault=true, http.status_code=409
- Action: Ignore for Alerting.
- Reasoning: High volumes of
VALIDATION_ERROR or CONFLICT usually indicate a buggy client or a user misusing the system, not a server outage. These should feed into Dashboards/Analytics, not PagerDuty.
Scenario B: "The Cascade" (External Fault)
- Tags:
error.type=external, error.code=UPSTREAM_TIMEOUT
- Action: Page On-Call (Warn Level).
- Reasoning: The code is working, but a dependency (e.g., Stripe, AWS S3) is down. The backend is correctly returning 502. The fix is usually to wait or failover, not to reboot the pod.
Scenario C: "The Logic Bomb" (Invariant Violation)
- Tags:
error.type=logic, http.status_code=422
- Action: Page On-Call (High Priority).
- Reasoning: An
InvariantViolation means the code assumptions are wrong (e.g., "Order total is negative"). This is a bug in the deployed code that requires a hotfix or rollback. It is distinct from a generic 500.
Scenario D: "The Meltdown" (Infra Fault)
- Tags:
error.type=infra, http.status_code=503
- Action: Page On-Call (Critical).
- Reasoning:
DatabaseConnectionException usually implies the DB is unreachable or the connection pool is exhausted. This requires immediate infrastructure intervention.
6. Implementation Snippet (Pseudo-code)
Here is how the handler enforces this taxonomy.
class ErrorHandlerMiddleware:
def handle(self, request, exception):
# 1. Lookup the exception in the Taxonomy Registry
mapping = TAXONOMY_MAP.get(type(exception), DEFAULT_500_MAP)
# 2. Construct Envelope
response = {
"type": f"https://api.io/errors/{mapping.code.lower()}",
"code": mapping.code,
"status": mapping.http_status,
"trace_id": request.trace_id,
"detail": str(exception) if mapping.expose_details else "Internal Error"
}
# 3. Emit Observability
logger.error(
message=f"Request failed: {mapping.code}",
error_type=mapping.obs_type,
error_code=mapping.code,
http_status=mapping.http_status,
is_user_fault=mapping.is_user_fault,
stack_trace=traceback.format_exc() # Keep for logs, not HTTP response
)
# 4. Return HTTP Response
return JsonResponse(response, status=mapping.http_status)