Okay, the user is asking for a structured backend error taxonomy that aligns domain exceptions, HTTP envelopes, and observability tags. This is a technical request about system design and error handling, likely from a backend engineer or architect. They want consistency in how errors are classified and reported across their stack.
First, I need to break down the three components they mentioned: domain exceptions (business logic errors), HTTP envelopes (API responses), and observability tags (logging/metrics). The taxonomy should bridge these so that when an error occurs, it maps cleanly to all three layers.
I recall common patterns like using error codes, severity levels, and categorization by impact (client vs. server). Maybe start with a high-level structure, then drill into specifics. The user probably wants something actionable—naming conventions, examples, maybe a mapping table.
Also, they mentioned "incident triage," so the taxonomy should help engineers quickly diagnose issues. That means including fields like triage_priority and suppression_rules. Observability tags need to be machine-parseable, so keys should be standardized.
I should suggest a layered approach: domain exceptions define the root cause, HTTP envelopes translate that to API consumers, and observability tags hook into monitoring tools. Examples will help—like a specific ValidationError mapping to HTTP 400 and certain tags.
Avoid overcomplicating; keep it pragmatic. Maybe include anti-patterns too, like leaking internal details in HTTP responses. Emphasize that domain exceptions should never be exposed raw.
The user might also need guidance on implementing this across services, so I’ll mention code structure and pipeline integration. Diagrams could be useful, but since this is text, I’ll describe relationships clearly.
Finally, summarize with a cheat sheet or matrix to show how everything connects. Make sure the taxonomy is extensible—new error types should fit the schema without breaking existing tooling.
Here is a comprehensive backend error taxonomy designed for consistent incident triage, aligning domain exceptions, HTTP response envelopes, and observability tags.
This taxonomy enforces the principle: "Define once, propagate consistently".
1. Core Principles & Philosophy
- Separation of Concerns: Domain exceptions represent business/technical failures. HTTP envelopes are a transport concern for API consumers. Observability tags are for machine analysis.
- Never Leak Internals: HTTP responses must never expose raw exception messages, stack traces, or internal class names to clients.
- Idempotent Causality: A single root-cause domain exception should deterministically map to one HTTP status code and a stable set of observability tags.
- Triage-First Design: All fields (
error_code, category, triage_priority) are optimized for filtering and alerting in monitoring tools (Grafana, Datadog, Splunk).
2. The Taxonomy Structure (Three Layers)
Layer 1: Domain Exception Hierarchy (Language/Framework Agnostic)
Define a base AppException that all service-specific exceptions inherit from. The key is the ErrorCode.
| Property | Type | Description | Example |
|---|
error_code | string (constant) | Primary key. Stable, semantics-first code. Format: DOMAIN.SUBSYSTEM.ACTION.ERROR_VARIANT. | PAYMENT.GATEWAY.CHARGE.INSUFFICIENT_FUNDS |
message | string | Human-readable, safe for logs. Never returned to client. | "Bank declined charge: insufficient funds for account ending 4242." |
category | enum | Broad classification for aggregation. | BUSINESS_RULE, VALIDATION, EXTERNAL_SERVICE, DATA_INTEGRITY, SYSTEM |
triage_priority | enum | Pre-defined severity for alert routing. | P0-CRITICAL, P1-HIGH, P2-MEDIUM, P3-LOW, P4-INFO |
is_retryable | boolean | Should the client safely retry? (Usually false for client errors). | false |
suppression_rules | list<string> | Tags for automated alert suppression (e.g., upstream:stripe-outage). | ["suppress_on:503_from_gateway"] |
http_status | int | Derived, not stored. Determined by a mapper function based on category and is_retryable. | 402 (from BUSINESS_RULE + is_retryable=false) |
Example Domain Exception:
public class InsufficientFundsException extends AppException {
public static final String ERROR_CODE = "PAYMENT.GATEWAY.CHARGE.INSUFFICIENT_FUNDS";
public InsufficientFundsException(String userId, String accountLast4) {
super(ERROR_CODE,
String.format("User %s account %s has insufficient funds.", userId, accountLast4),
category.BUSINESS_RULE,
triage_priority.P2,
false);
}
}
Layer 2: HTTP Response Envelope (API Contract)
The standardized JSON structure returned for all non-2xx responses.
{
"error": {
"code": "PAYMENT.GATEWAY.CHARGE.INSUFFICIENT_FUNDS", // Domain's error_code
"message": "The payment method has insufficient funds. Please use a different card.", // Safe, client-facing message.
"request_id": "req_abc123", // Correlation ID from entry request
"details": {
"field": "card_id", // Optional: for validation errors
"suggested_fix": "Retry with a valid payment method"
}
}
}
HTTP Status Code Mapping Rules:
Domain category | is_retryable | HTTP Status | Rationale |
|---|
VALIDATION | N/A | 400 Bad Request | Client sent malformed data. |
AUTHORIZATION / AUTHENTICATION | N/A | 401 / 403 | Identity/scope failure. |
BUSINESS_RULE | false | 402 Payment Required / 409 Conflict | Valid request, but business logic forbids it. |
BUSINESS_RULE | true | 429 Too Many Requests | Rate limit or quota breach. |
RESOURCE_NOT_FOUND | N/A | 404 Not Found | |
EXTERNAL_SERVICE | true | 502 Bad Gateway / 504 Gateway Timeout | Our service is fine, upstream is failing. |
EXTERNAL_SERVICE | false | 503 Service Unavailable | Upstream is in a bad state we can't work around. |
DATA_INTEGRITY | false | 500 Internal Server Error | |
SYSTEM / UNEXPECTED | N/A | 500 Internal Server Error | Catch-all. |
Critical Rule: The envelope's error.code must always be a known domain error_code. For 500s from unknown exceptions, use a generic code like SYSTEM.UNHANDLED_ERROR and log the real exception.
Layer 3: Observability Tags (For Logs, Metrics, Traces)
These tags are attached to every log line, span, and metric generated from handling the exception. They enable powerful filtering.
| Tag Key | Value Source | Example Value | Purpose |
|---|
error.code | Domain error_code | PAYMENT.GATEWAY.CHARGE.INSUFFICIENT_FUNDS | Primary grouping key. |
error.category | Domain category | BUSINESS_RULE | Broad drill-down. |
error.triage_priority | Domain triage_priority | P2 | Alert routing. |
error.is_retryable | Domain is_retryable | false | Client behavior hint. |
http.status_code | Mapped HTTP code | 402 | Cross-correlate with access logs. |
service.name | Deployment config | payment-service | |
service.version | Deployment config | v2.4.1 | |
env | Deployment config | prod | |
suppression_rules | Domain list | suppress_on:503_from_gateway | Feed into silencing logic. |
user.id | Auth context | user_789 | (If available & PII-safe) |
account.id | Business context |
Log Example (JSON):
{
"timestamp": "2024-01-15T10:30:00Z",
"level": "ERROR",
"service": "payment-service",
"error.code": "PAYMENT.GATEWAY.CHARGE.INSUFFICIENT_FUNDS",
"error.category": "BUSINESS_RULE",
"error.triage_priority": "P2",
"http.status_code": 402,
"user.id": "user_789",
"message": "User user_789 account acct_123 payment method ending 4242 has insufficient funds.",
"stack_trace": "..."
}
3. Implementation Guide & Anti-Patterns
✅ Do:
- Centralize Mapping: Create a single
ExceptionMapper component that:
- Receives any
AppException.
- Returns the correct HTTP status (
getHttpStatus()).
- Generates the safe client message (can be a prop on exception or a lookup table).
- Injects all observability tags into the logging context (e.g., SLF4J MDC, OpenTelemetry attributes).
- Treat
error_code as immutable. Never change the semantic meaning of an existing code.
- Use
triage_priority to drive PagerDuty/Opsgenie routing.
- Log the domain exception's full details (including stack trace) at ERROR level, but ensure the HTTP response envelope is clean.
- Instrument metrics:
app.errors.total{error.code="...", error.category="...", http.status_code="402"} (Counter)
app.errors.unhandled.count (Counter for anything not an AppException)
❌ Avoid:
- Using HTTP status as the sole signal: Many different business errors map to
402 or 409. Group by error.code.
- Returning
exception.class.simpleName in the API: ("InsufficientFundsException") This leaks implementation details.
- Dynamic
error_code values: "PAYMENT_FAILED_REASON_XYZ" makes alerting impossible.
- Putting PII or secrets in
error.message or tags. (e.g., full credit card number, raw SQL query).
- Not mapping unchecked exceptions: Wrap all uncaught
RuntimeException/Throwable in a generic SYSTEM.UNHANDLED_ERROR domain exception at the outermost layer (e.g., filter, middleware).
4. Incident Triage Cheat Sheet
An engineer receiving an alert should immediately see:
| Signal | Where to Look | What It Means |
|---|
Spike in error.code=PAYMENT.GATEWAY.CHARGE.INSUFFICIENT_FUNDS | Metrics/Dashboards | Legitimate user behavior (many bad cards)? Or a bug in our validation? |
error.category=EXTERNAL_SERVICE + http.status_code=502 | Logs (filter tags) | Stripe/PayPal/etc is having an outage. Check their status page. |
error.triage_priority=P0 | Alerting platform | Immediate, critical failure requiring human intervention. |
error.code=SYSTEM.UNHANDLED_ERROR | Logs (search for this code) | New, unexpected bug. Start with stack trace. |
High rate of error.code=VALIDATION.REQUIRED_FIELD_MISSING | API metrics | Mobile app or client integration is broken. |
5. Sample Taxonomy Matrix (Partial)
Domain error_code | category | triage_priority | is_retryable | HTTP | Primary suppression_rules |
|---|
USER.AUTH.INVALID_CREDENTIALS | AUTHENTICATION | P2 | false | 401 | suppress_on:brute_force_pattern |
ORDER.INVENTORY.SOLD_OUT | BUSINESS_RULE | P2 | false | 409 | -- |
PAYMENT.GATEWAY.TIMEOUT | EXTERNAL_SERVICE | P1 | true | 504 | suppress_on:gateway_maintenance |
DATA.DB.CONNECTION_POOL_EXHAUSTED | SYSTEM | P0 | false | 500 | -- |
VALIDATION.REQUIRED_FIELD | VALIDATION | P3 | false | 400 | suppress_on:automated_test |
This taxonomy provides a single source of truth that synchronizes error semantics across your code, API contracts, and observability platform, drastically reducing triage time and cognitive load during incidents.