Handle errors so failures are visible and recoverable
Every error is a decision: recover, translate, or propagate. An empty catch makes that decision silently and wrongly. Design the error path with the happy path: typed errors with stable codes, context added on the way up with the cause preserved, and one place at the top that logs and decides what the caller sees.
Steps
- Map the failure modes. For the code the ticket touches, list what can fail:
invalid input, not found, conflict, permission, dependency down, timeout, and bugs.
For each, decide who must know (caller, user, operator) and whether anything can be
done. Call
search_lorefor the repo's error base class or result type and the API error envelope. - Use the repo's error shape. A typed error hierarchy or result type carrying a
stable machine code (
NOT_FOUND,CONFLICT) separate from the human message. Never throw strings. Use return values for expected outcomes where the language favours them (Goerror, RustResult) and exceptions for exceptional ones elsewhere. - Fail fast at boundaries. Validate input where it enters (the
security-input-validationskill) and reject with the documented code before any side effect. Inside the boundary, trust your own types. - Wrap with context, keep the cause. Add what the caller needs (which record, which
operation) and preserve the original:
- JavaScript/TypeScript:
new AppError(msg, { cause: err }); neverthrow "msg". - Python:
raise AppError(msg) from err;add_note()for context. - Go:
fmt.Errorf("load order %s: %w", id, err); test witherrors.Is/errors.As; never compare error strings. - Rust:
?withthiserrortypes in libraries,anyhow::Contextin binaries; nounwrap()on fallible runtime paths. - Java/Kotlin: pass the cause to the constructor; C#:
throw;to rethrow, neverthrow ex;(it resets the stack trace).
- JavaScript/TypeScript:
- Recover only where recovery is real. Retry only transient failures of idempotent
operations, with backoff, jitter and a cap (the
idempotency-and-retriesskill). Fall back only when the degraded result is acceptable and is logged or counted. Otherwise propagate. An emptycatch,except: pass,except Exceptionthat continues, an ignorederr, or.catch(() => {})is a bug: handle it or delete it. Do not catch an error to hide a race or a bug (e.g. retrying on a temp-file collision instead of fixing it with theconcurrency-and-asyncskill). - Leave no half-applied state. Fail before the first side effect, or make the
sequence atomic (one transaction), or compensate explicitly. Release resources in
finally/defer/using/with. - Report once, at the top. The outermost handler (request middleware, job runner,
CLI
main) logs once with code, context, cause chain and correlation id through the structured logger (thestructured-logging-and-tracingskill); intermediate layers wrap, they do not log and rethrow. It maps typed errors to the external contract: for HTTP, the repo's envelope or RFC 9457 problem details (type,title,status,detail) with the right status (400/422 validation, 404, 409 conflict, 503 dependency unavailable, 500 only for bugs). Stack traces, SQL, file paths and secrets never reach a client. Install process-level handlers (unhandled rejection, uncaught exception, panic recovery at the goroutine or request boundary) that log and exit or fail the request, never continue in an unknown state. - Test the error paths as first-class cases, one test per AC exercising the AC's own behaviour: each failure mode asserts the error code or status, the body shape, that the cause is preserved (or logged), and that no partial write or side effect happened. Inject failures with fakes or fault hooks, not by editing production code.
- Evidence with the
record-evidenceskill.
Done when
- Every failure mode from step 1 has a typed error, a mapping at the top, and a test.
- No swallowed errors remain in the touched code (search for empty catches,
pass,_ = err,.catch(() => {})). - Client responses contain stable codes and no internals; each error is logged once.
Anti-patterns
catch (e) { log(e); throw e; }at every layer (the same error logged five times).- Mapping every exception to
500, or every exception to400. - Retrying non-idempotent writes; retrying without a cap.
- Wrapping that drops the cause; matching on error message text.
Capture lore
This skill is one of the places durable, reusable knowledge naturally surfaces:
While mapping failure modes you learn the repo's error codes and envelope and how each dependency actually fails. That kind of fact is lore. Capture it via the lore-capture
protocol in your brief (CLAUDE.factory.md, step 11 "Memory contribution"):
call the Memory MCP suggest_lore once at the close of your work — reusable
conventions, gotchas, decisions, and boundaries only, never per-ticket trivia.
