Whetstone
0day streak

Error Handling

Failing usefully, and where to put the recovery.

14

Questions

6/5/3

Easy / Med / Hard

Your accuracy

Error handling is a design decision about where failure is dealt with, not a formality bolted on at the end.

Fail fast. Detect an invalid state at the earliest point and stop. Code that limps on with bad data produces a failure far from its cause, and the stack trace points at the symptom rather than the bug.

Exceptions versus result types. Exceptions separate the happy path from error handling and are invisible in a function signature, so a caller cannot tell what might be thrown. Result types make failure part of the return value, so the compiler forces you to deal with it, at the cost of noisier code. Neither is universally right; consistency within a codebase matters more than the choice.

Distinguish expected failures from bugs. A user submitting an invalid email is an expected outcome and belongs in the return type. A null where the invariants say null is impossible is a bug, and should be loud. Treating both as exceptions means the log fills with normal events and real problems disappear into the noise.

Swallowing exceptions is the worst common practice in the language. An empty catch block converts a failure into wrong behaviour later, with the evidence deleted. If you genuinely can ignore it, say why in a comment.

Handle errors where you can actually do something. Catching, logging, and rethrowing at every layer produces the same error logged six times and no decision made. Let it propagate to the level that can retry, fall back, or tell the user.

Retries belong at exactly one level. Retry at the HTTP client, the service, and the job runner and three attempts become twenty-seven. Pick a layer, use exponential backoff with jitter, and cap it.

Only retry what is safe to repeat. That means idempotent operations, or non-idempotent ones carrying an idempotency key. Retrying a payment without one is how customers get charged twice.

Graceful degradation beats total failure: a recommendations service being down should mean no recommendations, not no page.