# Error Patterns — Derived Rules > Derives from `domains/errors/first-principles.md`. Common error-handling patterns and when to use them. ## Pattern 1: Result Type (P1 Errors are Data) ```typescript type Result = { ok: true; value: T } | { ok: false; error: E }; function divide(a, b): Result { if (b === 0) return { ok: false, error: "division by zero" }; return { ok: true, value: a / b }; } ``` - Errors are values, not exceptions. The caller handles them explicitly. - Use when errors are expected (parsing, validation, fallible operations). - Avoid when errors are truly exceptional (out of memory, programmer error) — use exceptions/panics. ## Pattern 2: Sentinel Error (P4 Preserve Context) ```go var ErrNotFound = errors.New("not found") if errors.Is(err, ErrNotFound) { ... } ``` - A sentinel is a known error value the caller checks against. - Use for a small, known set of error conditions. - Wrap with context: `fmt.Errorf("load user %d: %w", id, ErrNotFound)`. ## Pattern 3: Typed Error (P1, P3 Fail Specifically) ```rust enum AppError { NotFound(String), Invalid(String), Internal(String), } ``` - A typed error carries the kind and the detail. - The caller matches on kind; the detail is for logging/display. - Use when there are distinct error categories the caller handles differently. ## Pattern 4: Error Wrapping (P4 Preserve Context) ```go return fmt.Errorf("query users: %w", err) ``` - Wrap errors as they cross boundaries. The outer error says "what was happening"; the inner says "what went wrong." - The error chain is the stack trace of intent. Read it top-down: "I was doing X, which failed because Y, which was caused by Z." - Never wrap with a generic message ("operation failed"). Wrap with the specific operation. ## Pattern 5: Fail Fast (P6 Unrecoverable Means Stop) ```typescript if (config.secret === undefined) throw new Error("config.secret is required"); ``` - For unrecoverable conditions, fail immediately. Do not limp on. - Use at startup: missing required config, missing database, missing secrets. - Do not use for recoverable conditions (a 404 is recoverable; a missing secret is not). ## Pattern 6: Retry with Backoff (P5 Recoverable When Possible) ```python for attempt in range(3): try: return do_thing() except TransientError: sleep(2 ** attempt) raise PermanentError() ``` - Retry transient errors (network, 429, 5xx). Do not retry permanent errors (400, 401). - Exponential backoff with jitter. A retry storm is worse than the original failure. - Bounded retries. Infinite retry is infinite hang (P8 Timeout Discipline). ## Pattern 7: Circuit Breaker (P3 Defense in Depth via errors P7) - After N consecutive failures, stop trying. Return a fallback or error immediately. - Use for external dependencies (a downstream service, an API). - The breaker resets after a cooldown. Protects the system and the downstream. ## What Violates Error Patterns | Violation | Pattern | |-----------|---------| | `catch (e) { return null }` | (anti-pattern, P2 Fail Loudly) | | `throw new Error("error")` | P3 Fail Specifically | | Retry without backoff | P5, P8 | | `return null` for "not found" | P1 (errors are data, not absence) | | `throw` in a recovery path | P6 (fail fast in the wrong place) |