Error Handling
Intro
Errors are part of the type system, not an afterthought. Make
failure paths explicit, separate user-facing messages from internal
diagnostics, and reach for retries and circuit breakers only when
the failure is genuinely transient.
Overview
Result types vs exceptions
Use algebraic types where the language supports them — they make
error paths explicit in the signature.
- Rust:
Result<T, E> for recoverable errors, Option<T> for
missing values. Propagate with ?. Define domain error enums
with thiserror.
- TypeScript: discriminated unions or a
Result<T, E> library.
Avoid throw for expected failures (validation, not-found).
Reserve exceptions for truly unexpected conditions.
- Python: exceptions are idiomatic, but consider returning
None or a result tuple in tight loops where try/except overhead
matters.
- Java: checked exceptions for recoverable conditions the
caller must handle, unchecked (
RuntimeException) for
programming errors. Prefer specific types over Exception.
Error hierarchies
Design errors in layers:
- Domain errors — business rule violations
(
InsufficientFunds, ItemOutOfStock).
- Application errors — workflow failures (
OrderNotFound,
Unauthorized).
- Infrastructure errors — external system failures
(
DatabaseUnavailable, TimeoutError).
Each layer exposes only errors meaningful at that level.
Infrastructure errors are mapped to application errors before
reaching the domain.
User-facing vs internal
Never leak stack traces, SQL, or file paths to end users.
- Internal errors: full context for debugging — stack trace,
request ID, input values.
- User-facing errors: human-readable message, error code,
optional field-level details.
- Map at the boundary (HTTP handler, CLI output). Log the internal
error with a correlation ID; return the ID to the user for
support.
Error codes and structured responses
Use namespaced, stable error codes (PAYMENT.DECLINED,
AUTH.TOKEN_EXPIRED, VALIDATION.FIELD_REQUIRED). Document them
in a central registry. Never reuse or rename codes once shipped.
For APIs, return a consistent error shape:
{
"error": {
"code": "VALIDATION.FIELD_REQUIRED",
"message": "The 'email' field is required.",
"details": [
{ "field": "email", "reason": "required" }
],
"request_id": "req-abc123"
}
}
Retries and circuit breakers
Retry only transient failures (network timeouts, 503s, lock
contention). Use exponential backoff with jitter: base delay
100–500ms, multiply by 2 each attempt, add random jitter (0–100% of
delay) to prevent thundering herd. Cap retries (3–5) and total
timeout. Never retry 4xx client errors (except 429), validation
failures, or auth errors.
Circuit breakers prevent cascading failures when a downstream
service is unhealthy:
- Closed (normal): requests flow through; track failure rate.
- Open (tripped): requests fail immediately; return a fallback.
- Half-open (probing): allow one request after a timeout. On
success, close. On failure, reopen.
Configure failure threshold (e.g. 5 failures in 30s), open duration
(e.g. 60s), and half-open probe count.
Gotchas
Agent-specific failure modes — provider-neutral pause-and-self-check items:
- Catching
Exception (or bare except:) and swallowing it. Silent error swallowing is the most common cause of production mysteries where "nothing went wrong, but nothing worked either." Catch specific error types; log and re-raise everything else.
- Leaking stack traces, SQL, or file paths in HTTP responses. Internal error details in user-facing responses are both a security vulnerability and a poor user experience. Map internal errors to user-facing codes at the boundary; log the full context internally with a correlation ID.
- Retrying non-idempotent operations without a deduplication key. Retrying a payment, an email send, or an inventory decrement without idempotency protection causes double-charges and double-sends. Add an idempotency key at the call site before wiring retry logic.
- Retrying 4xx errors as if they were transient. A 400 (bad request) or 401 (unauthorized) will not change on retry — it reflects a problem with the request, not the server. Retry only transient failures: 429, 500, 502, 503, 504, and network-level errors.
- Retrying without exponential backoff and jitter. Fixed-interval retries on a struggling service create a thundering herd that prevents recovery. Use exponential backoff with random jitter; cap the total number of retries and the total elapsed time.
- Sentinel return values instead of explicit errors. Returning
-1, null, or an empty string to signal failure requires every caller to know and check the convention. Make failure explicit in the type: Result<T, E>, Option<T>, or a domain error type.
- Renaming or reusing error codes after shipping. Error codes are a public contract. Consumers build conditional logic on them. Renaming
PAYMENT.DECLINED or reusing a retired code silently breaks consumer error handling.
Full reference
Error reporting
- Log with structured fields:
level, error_code, message,
stack, request_id, user_id.
- Send unhandled exceptions to an error tracker (Sentry, Datadog,
Honeybadger).
- Alert on error rate spikes, not individual errors.
- Group errors by root cause, not by message string.
Domain error enum (Rust)
use thiserror::Error;
#[derive(Error, Debug)]
pub enum PaymentError {
#[error("insufficient funds: required {required}, available {available}")]
InsufficientFunds { required: u64, available: u64 },
#[error("card declined: {reason}")]
CardDeclined { reason: String },
#[error("payment provider unavailable")]
ProviderUnavailable(#[source] reqwest::Error),
}
pub fn charge(amount: u64, balance: u64) -> Result<Receipt, PaymentError> {
if amount > balance {
return Err(PaymentError::InsufficientFunds {
required: amount,
available: balance,
});
}
Ok(Receipt { amount })
}
Retry with backoff (Python)
import time
import random
import httpx
def fetch_with_retry(url: str, max_retries: int = 4) -> httpx.Response:
base_delay = 0.3
for attempt in range(max_retries + 1):
try:
resp = httpx.get(url, timeout=5.0)
if resp.status_code == 429:
retry_after = float(resp.headers.get("Retry-After", base_delay))
time.sleep(retry_after + random.uniform(0, 0.5))
continue
resp.raise_for_status()
return resp
except httpx.TransportError:
if attempt == max_retries:
raise
delay = base_delay * (2 ** attempt) + random.uniform(0, base_delay)
time.sleep(delay)
raise httpx.HTTPError(f"Failed after {max_retries} retries")
Structured API error response (TypeScript)
class AppError extends Error {
constructor(
public code: string,
message: string,
public statusCode: number = 500,
public details?: { field: string; reason: string }[],
) {
super(message);
}
}
// In route handler
app.post("/orders", async (req, res) => {
try {
const order = await createOrder(req.body);
res.status(201).json(order);
} catch (err) {
if (err instanceof AppError) {
res.status(err.statusCode).json({
error: {
code: err.code,
message: err.message,
details: err.details,
request_id: req.id,
},
});
} else {
console.error("Unhandled error", { request_id: req.id, err });
res.status(500).json({
error: {
code: "INTERNAL.UNEXPECTED",
message: "An unexpected error occurred.",
request_id: req.id,
},
});
}
}
});
Anti-patterns
- Catching
Exception (or bare except:) and swallowing it
- Returning sentinel values (
-1, empty string) instead of an
explicit error
- Leaking SQL, stack traces, or filesystem paths in HTTP responses
- Retrying non-idempotent operations without a deduplication key
- Retrying 4xx errors as if they were transient
- Renaming or reusing error codes after shipping them
- Alerting on every individual error instead of rate spikes
1---2name: error-handling3description: |4 Error handling across languages — Result types, exceptions, retries, circuit breakers, and structured error responses. Use when designing error handling for a module or service, choosing between Result types and exceptions, building error hierarchies, implementing retries or circuit breakers, or reviewing code for missing or poor error handling.5metadata:6 source: https://skillmd.com/skills/projectious-work/error-handling7 processkit:8 apiVersion: processkit.projectious.work/v19 id: SKILL-error-handling10 version: "1.1.0"11 created: 2026-04-06T00:00:00Z12 category: engineering13---1415# Error Handling1617## Intro1819Errors are part of the type system, not an afterthought. Make20failure paths explicit, separate user-facing messages from internal21diagnostics, and reach for retries and circuit breakers only when22the failure is genuinely transient.2324## Overview2526### Result types vs exceptions2728Use algebraic types where the language supports them — they make29error paths explicit in the signature.3031- **Rust:** `Result<T, E>` for recoverable errors, `Option<T>` for32 missing values. Propagate with `?`. Define domain error enums33 with `thiserror`.34- **TypeScript:** discriminated unions or a `Result<T, E>` library.35 Avoid `throw` for expected failures (validation, not-found).36 Reserve exceptions for truly unexpected conditions.37- **Python:** exceptions are idiomatic, but consider returning38 `None` or a result tuple in tight loops where try/except overhead39 matters.40- **Java:** checked exceptions for recoverable conditions the41 caller must handle, unchecked (`RuntimeException`) for42 programming errors. Prefer specific types over `Exception`.4344### Error hierarchies4546Design errors in layers:47481. **Domain errors** — business rule violations49 (`InsufficientFunds`, `ItemOutOfStock`).502. **Application errors** — workflow failures (`OrderNotFound`,51 `Unauthorized`).523. **Infrastructure errors** — external system failures53 (`DatabaseUnavailable`, `TimeoutError`).5455Each layer exposes only errors meaningful at that level.56Infrastructure errors are mapped to application errors before57reaching the domain.5859### User-facing vs internal6061Never leak stack traces, SQL, or file paths to end users.6263- **Internal errors:** full context for debugging — stack trace,64 request ID, input values.65- **User-facing errors:** human-readable message, error code,66 optional field-level details.67- Map at the boundary (HTTP handler, CLI output). Log the internal68 error with a correlation ID; return the ID to the user for69 support.7071### Error codes and structured responses7273Use namespaced, stable error codes (`PAYMENT.DECLINED`,74`AUTH.TOKEN_EXPIRED`, `VALIDATION.FIELD_REQUIRED`). Document them75in a central registry. Never reuse or rename codes once shipped.7677For APIs, return a consistent error shape:7879```json80{81 "error": {82 "code": "VALIDATION.FIELD_REQUIRED",83 "message": "The 'email' field is required.",84 "details": [85 { "field": "email", "reason": "required" }86 ],87 "request_id": "req-abc123"88 }89}90```9192### Retries and circuit breakers9394Retry only transient failures (network timeouts, 503s, lock95contention). Use exponential backoff with jitter: base delay96100–500ms, multiply by 2 each attempt, add random jitter (0–100% of97delay) to prevent thundering herd. Cap retries (3–5) and total98timeout. **Never retry** 4xx client errors (except 429), validation99failures, or auth errors.100101Circuit breakers prevent cascading failures when a downstream102service is unhealthy:103104- **Closed** (normal): requests flow through; track failure rate.105- **Open** (tripped): requests fail immediately; return a fallback.106- **Half-open** (probing): allow one request after a timeout. On107 success, close. On failure, reopen.108109Configure failure threshold (e.g. 5 failures in 30s), open duration110(e.g. 60s), and half-open probe count.111112## Gotchas113114Agent-specific failure modes — provider-neutral pause-and-self-check items:115116- **Catching `Exception` (or bare `except:`) and swallowing it.** Silent error swallowing is the most common cause of production mysteries where "nothing went wrong, but nothing worked either." Catch specific error types; log and re-raise everything else.117- **Leaking stack traces, SQL, or file paths in HTTP responses.** Internal error details in user-facing responses are both a security vulnerability and a poor user experience. Map internal errors to user-facing codes at the boundary; log the full context internally with a correlation ID.118- **Retrying non-idempotent operations without a deduplication key.** Retrying a payment, an email send, or an inventory decrement without idempotency protection causes double-charges and double-sends. Add an idempotency key at the call site before wiring retry logic.119- **Retrying 4xx errors as if they were transient.** A 400 (bad request) or 401 (unauthorized) will not change on retry — it reflects a problem with the request, not the server. Retry only transient failures: 429, 500, 502, 503, 504, and network-level errors.120- **Retrying without exponential backoff and jitter.** Fixed-interval retries on a struggling service create a thundering herd that prevents recovery. Use exponential backoff with random jitter; cap the total number of retries and the total elapsed time.121- **Sentinel return values instead of explicit errors.** Returning `-1`, `null`, or an empty string to signal failure requires every caller to know and check the convention. Make failure explicit in the type: `Result<T, E>`, `Option<T>`, or a domain error type.122- **Renaming or reusing error codes after shipping.** Error codes are a public contract. Consumers build conditional logic on them. Renaming `PAYMENT.DECLINED` or reusing a retired code silently breaks consumer error handling.123124## Full reference125126### Error reporting127128- Log with structured fields: `level`, `error_code`, `message`,129 `stack`, `request_id`, `user_id`.130- Send unhandled exceptions to an error tracker (Sentry, Datadog,131 Honeybadger).132- Alert on error rate spikes, not individual errors.133- Group errors by root cause, not by message string.134135### Domain error enum (Rust)136137```rust138use thiserror::Error;139140#[derive(Error, Debug)]141pub enum PaymentError {142 #[error("insufficient funds: required {required}, available {available}")]143 InsufficientFunds { required: u64, available: u64 },144145 #[error("card declined: {reason}")]146 CardDeclined { reason: String },147148 #[error("payment provider unavailable")]149 ProviderUnavailable(#[source] reqwest::Error),150}151152pub fn charge(amount: u64, balance: u64) -> Result<Receipt, PaymentError> {153 if amount > balance {154 return Err(PaymentError::InsufficientFunds {155 required: amount,156 available: balance,157 });158 }159 Ok(Receipt { amount })160}161```162163### Retry with backoff (Python)164165```python166import time167import random168import httpx169170def fetch_with_retry(url: str, max_retries: int = 4) -> httpx.Response:171 base_delay = 0.3172 for attempt in range(max_retries + 1):173 try:174 resp = httpx.get(url, timeout=5.0)175 if resp.status_code == 429:176 retry_after = float(resp.headers.get("Retry-After", base_delay))177 time.sleep(retry_after + random.uniform(0, 0.5))178 continue179 resp.raise_for_status()180 return resp181 except httpx.TransportError:182 if attempt == max_retries:183 raise184 delay = base_delay * (2 ** attempt) + random.uniform(0, base_delay)185 time.sleep(delay)186 raise httpx.HTTPError(f"Failed after {max_retries} retries")187```188189### Structured API error response (TypeScript)190191```typescript192class AppError extends Error {193 constructor(194 public code: string,195 message: string,196 public statusCode: number = 500,197 public details?: { field: string; reason: string }[],198 ) {199 super(message);200 }201}202203// In route handler204app.post("/orders", async (req, res) => {205 try {206 const order = await createOrder(req.body);207 res.status(201).json(order);208 } catch (err) {209 if (err instanceof AppError) {210 res.status(err.statusCode).json({211 error: {212 code: err.code,213 message: err.message,214 details: err.details,215 request_id: req.id,216 },217 });218 } else {219 console.error("Unhandled error", { request_id: req.id, err });220 res.status(500).json({221 error: {222 code: "INTERNAL.UNEXPECTED",223 message: "An unexpected error occurred.",224 request_id: req.id,225 },226 });227 }228 }229});230```231232### Anti-patterns233234- Catching `Exception` (or bare `except:`) and swallowing it235- Returning sentinel values (`-1`, empty string) instead of an236 explicit error237- Leaking SQL, stack traces, or filesystem paths in HTTP responses238- Retrying non-idempotent operations without a deduplication key239- Retrying 4xx errors as if they were transient240- Renaming or reusing error codes after shipping them241- Alerting on every individual error instead of rate spikes