Tags

Error Handling

Error Handling

0 lessons
7 code snippets
1 question bank
1 system design
9 community items

error-handling

Code Snippets

7 snippets
Code Snippet

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.

JavaScript
utility
code-template
error-handling
retry-policy

855

15

Medium
Code Snippet

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.

JavaScript
async-programming
promises
utility
error-handling

737

15

Easy
Code Snippet

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.

JavaScript
async-programming
promises
utility
error-handling

622

20

Medium
Code Snippet

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.

JavaScript
async-programming
js-fetch-api
utility
error-handling

1k

6

Medium
Code Snippet

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.

Java
java-optionals
error-handling
implementation

1k

13

Easy
Code Snippet

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.

Java
java-exception-handling
error-handling
java-file-io

1.1k

26

Medium
Code Snippet

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.

Go
go-error-handling
error-handling
implementation

1k

7

Easy

Community

9 items
Code Snippet

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.

JavaScript
openai
sse
networking
error-handling

250

3

4.4 (12)

May 15, 2026

by @oliviadelgado

Question Bundle
$14.99

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.

JavaScript
react
hooks
interview-prep
error-handling

1k

27

4.2 (15)

Apr 28, 2026

by @ethandubois

Code Snippet

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.

JavaScript
http
error-handling
code-template
utility

1k

32

4.2 (9)

Apr 13, 2026

by @leoeriksson

Code Snippet

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.

TypeScript
logging
security
error-handling
code-template

434

14

4.4 (15)

Mar 6, 2026

by @nadiaali

Code Snippet

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.

JavaScript
react
hooks
code-template
error-handling

729

13

4.5 (10)

Feb 23, 2026

by @leoeriksson

Code Snippet

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.

Python
openai
security
code-template
error-handling

1k

10

4.4 (15)

Feb 4, 2026

by @elisehuang

Code Snippet

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.

JavaScript
react
hooks
error-handling
optimistic-ui

582

8

4.7 (9)

Jan 28, 2026

by @laylabauer

Code Snippet

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.

JavaScript
debugging
error-handling
source-maps
utility

1.1k

17

4.3 (11)

Jan 20, 2026

by @kwamehenderson

Article

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.

error-handling
rest-api
api-design
http
backend

492

10

Jan 14, 2026

by @leoeriksson