Implementing Error Handling Patterns

1. Error Response Standardization Pattern

FieldDetail
codeMachine-readable error code (string enum)
messageHuman-readable summary
detailsField-level errors / context
traceIdFor support correlation
timestampISO 8601 UTC
documentation_urlLink to error reference

2. Problem Details Pattern

Field (RFC 9457)Purpose
typeURI identifying problem type
titleShort summary
statusHTTP status
detailSpecific occurrence info
instanceURI of this occurrence
Content-Typeapplication/problem+json

Example: Problem Details Response

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json

{
  "type": "https://api.shop.com/problems/validation",
  "title": "Validation Failed",
  "status": 422,
  "detail": "Order must contain at least 1 item",
  "instance": "/orders/req_a8f2",
  "errors": [{ "field": "items", "code": "min_size", "min": 1 }]
}

3. Error Code Pattern

Code StyleExample
Hierarchical Stringorder.payment.declined
Numeric40012 (HTTP-style 5-digit)
Service PrefixORDER-1042
StableNever reuse code; document deprecation

4. Error Propagation Pattern

PracticeDetail
Translate at BoundaryMap domain errors to HTTP/gRPC at edge
Preserve CauseOriginal error wrapped (stack trace logged)
Don't Leak InternalsDon't expose stack traces / SQL to clients
Carry Trace IDAlways

5. Fail Fast Pattern

AspectDetail
Validate EarlyReject malformed input at entry
Reject QuicklyReturn 4xx without downstream calls
BenefitSaves resources; better UX

6. Fail Silent Pattern

Use WhenDetail
Non-Critical PathTelemetry, optional enrichment
Background RefreshCache refresh failure → keep stale
AlwaysLog internally; never silently drop user-visible errors

7. Default Response Pattern

StrategyExample
Empty DefaultReturn [] when search fails
Cached DefaultReturn last-good response
Static StubHardcoded safe fallback
PartialReturn whatever succeeded

8. Error Recovery Pattern

MechanismDetail
RetryTransient errors with backoff
FailoverSwitch to secondary
CompensateUndo prior side-effects
Graceful DegradationReduced feature mode
Manual RecoveryDLQ + ops console

9. Compensating Action Pattern

AspectDetail
DefinitionSpecific action that undoes a prior side-effect
ExamplesRefund, release reservation, send correction email
IdempotentRequired (compensations may retry)
LoggedFor audit and forensics

10. Error Callback Pattern

AspectDetail
MechanismAsync failure notified via callback URL / event
ExamplesWebhook for failed batch job, error topic
IncludesJob ID, error code, retry instructions
SecuritySign callbacks (HMAC) to prove origin