Error Handling
error-handling
Code Snippets
Retry with Exponential Backoff
Network calls and flaky integrations need a retry wrapper, but plain retries hammer the same endpoint and amplify outages. Exponential backoff doubles the wait between attempts so transient failures recover fast and persistent failures don't DDoS the upstream. This snippet covers the canonical retry, a jittered version that prevents thundering-herd retries across clients, and a policy-driven variant that lets the caller decide which errors are retryable.
Timeout a Promise
A promise that never settles will leak handles and stall UI flows; wrapping it with a deadline turns a bug into a recoverable error. This snippet shows the classic `Promise.race` pattern, then upgrades it to clean up the timer on success and to forward an `AbortSignal` so cancelled work stops doing real I/O. Use it around any `fetch`, DB call, or third-party SDK that does not expose a native timeout option.
Partition allSettled Results
`Promise.allSettled` is the right call for partial-success workflows, but its `{ status, value, reason }` shape is awkward to consume directly. This snippet wraps it with a partitioner that returns `{ values, errors }` so the happy path stays simple, then layers in input-aware error reports that pair each failure with the original argument. Use it for fan-out fetches, batched writes, or any spot where one bad item should not poison the whole batch.
Cancellable fetch with AbortController
Every modern UI eventually needs to cancel in-flight requests: a search box that fires on every keystroke, a route change that abandons a partially loaded page, a tab close that should free sockets. `AbortController` is the standard primitive for this. This snippet covers the minimal abort pattern, a `fetchWithTimeout` helper that aborts on a deadline, and a hook-friendly cleanup pattern that pairs each request with its own controller.
Optional orElseGet Patterns
`Optional` makes the absence of a value explicit, but the `orElse` vs `orElseGet` choice trips people up. This snippet contrasts the two, shows `orElseThrow` for required-value contracts, and demonstrates `map`/`flatMap` chaining for null-safe field access. Reach for `orElseGet` whenever the default is expensive to compute.
try-with-resources Pattern
`try-with-resources` (Java 7+) automatically closes any object that implements `AutoCloseable` when the block exits, normally or via exception. This snippet covers the basic form, declaring multiple resources, the Java 9 enhancement that lets you reuse an existing variable, and writing your own `AutoCloseable` to participate in the pattern. Use it for every reader, writer, stream, lock, and database connection you open.
Idiomatic Go Error Handling
Go has no exceptions; errors are values returned alongside the result. This snippet covers the canonical `if err != nil` check, error wrapping with `fmt.Errorf("...: %w", err)` (Go 1.13+) for context, and unwrapping with `errors.Is` / `errors.As` to inspect underlying error types. Get this right and your stack of error returns will read as cleanly as any try/catch.
Community
Streaming LLM Response Consumer With Cancel
When a user navigates away mid-completion we still get billed for the remaining tokens. This is the SSE-style consumer I wrote that decodes JSON deltas, exposes a `cancel()` that aborts the request, and never leaks a reader on errors.
The React Bugs I Keep Finding in Pull Requests
I review React PRs all week. These 5 bugs keep showing up: a memo that does nothing, a useCallback hiding the real fix, a SyntheticEvent that vanishes, a stale closure interval, and a batching surprise. Each one is the actual diff I left.
The Fetch Wrapper I Keep in Every Project
My zero-dep `apiFetch` for Node and the browser. Adds a per-request timeout, retries with jittered backoff on 5xx and network failures, parses JSON, and attaches an auth token without leaking it into errors.
A Request/Response Logger That Does Not Leak Secrets
The redact-by-key logger I add to every Node service before it touches production logs. Catches headers, JWTs, card numbers, and Stripe keys without paying for a SIEM scrubber.
useFormField Hook With Field-Level Validation
A field-scoped form hook for the cases where react-hook-form is overkill. Tracks value, touched, blur, and an async validator with a single race-safe in-flight token.
A Prompt Template With Safe Interpolation
After a customer email leaked into a system prompt and changed the model's persona, I built a 30-line template that quotes user input, fences code, and refuses unknown placeholders. Use it before every LLM call.
useOptimisticMutation Hook With Rollback
My take on optimistic UI before React 19's `useOptimistic` was usable. The hook applies the change locally, fires the network call, and rolls back on failure with the original snapshot intact.
Resolving a Production Stack Trace Against a Source Map
When a minified Sentry stack only points at `bundle.js:1:140183`, this is the zero-dep VLQ decoder I drop in to map every frame back to a real source line.
Error Handling in REST APIs: The Shape I Settled On
RFC 7807 plus a code, requestId, errors array, and documentationUrl. The eight fields earning their keep, the status codes everyone confuses, and what changed my mind across four APIs.
