How to Structure Error Responses for APIs
Return consistent, machine-readable error objects with a code, message, details, and request ID so clients can handle errors programmatically.
Step-by-step guides and in-depth articles to level up your skills.
Page 5 of 9
Return consistent, machine-readable error objects with a code, message, details, and request ID so clients can handle errors programmatically.
Localize validation messages by passing a message key and parameters to the schema, then resolving them through a translation function at render time.
Validate untrusted request bodies with JSON Schema at the API boundary, reuse the schema for client forms, and evolve it with compatibility checks.
Resume a large upload after a drop by tracking confirmed ranges, re-requesting only the missing part, and verifying the assembled file with a checksum.
Queue multiple uploads with a bounded concurrency, retry each independently, and report per-file and overall progress without blocking the UI thread.
Compose nested Zod schemas for deeply structured forms, discriminate unions, and surface field-level errors with type-safe parse results.
Bundle a Node CLI into a single file with esbuild, mark node deps external, and add a shebang so the output runs as a bin on any machine with Node.
Partition resources like connection pools by tenant or feature so a flood in one cannot starve the others, and a failure stays contained.
Propagate an AbortSignal through async layers so a user cancel stops all in-flight work, and each layer cleans up on abort.
Color CLI output with Chalk to signal severity, keep color optional with a no-color flag, and structure lines so they parse as well as they read.
Wrap a flaky call in a circuit breaker that trips after N failures, half-opens to test recovery, and fails fast instead of queuing doomed calls.
Parse argv with a typed schema so flags become typed values, unknown flags fail, and a usage message prints on a parse error.
Load CLI config from a file with layered overrides for flags and env, validate it with a schema, and fail closed on an invalid config.
Report progress for a long CLI task with a single-line spinner or a bar, throttle redraws, and clear the line on completion for clean logs.
Generate a project scaffold from templates with variable substitution, conditional files, and a post-install hook so the user gets a runnable project.
Structure a CLI with Commander subcommands, share options, and keep help readable as the command tree grows beyond a handful of actions.
Bound concurrency with a pool so you do not trip connection limits or saturate bandwidth, and let the rest queue until a slot opens.
Retry transient failures with backoff, give up after a budget, and render a retry-able error boundary instead of a blank page when the budget is spent.
When a dependency is down, serve a cached or partial result with a banner rather than failing the whole page, and keep the write path honest.
Paginate a GraphQL list with cursors rather than offsets so inserts during paging do not shift the window, using the Relay connection spec.
Expose liveness and readiness probes with different meanings, keep them cheap, and never let them depend on a slow dependency.
Load more as the user scrolls with an IntersectionObserver sentinel, keep the query key stable, and avoid fetching the same page twice on overlapping events.
Add interactive prompts with Inquirer for choices, confirmations, and multi-select, with sensible defaults so the CLI works non-interactively too.
Choose the right claims for a JWT, use registered names like sub and exp, add custom claims for authorization, and keep the payload small and non-sensitive.
Rotate refresh tokens on each use, detect reuse as a theft signal, and keep access tokens short without forcing re-login on every call.
Compare stateless JWT sessions against server-side sessions, weigh revocation and size against lookup cost, and pick based on who verifies and how you log out.
Scope a JWT to a tenant with a tid claim, enforce tenant isolation in every query, and prevent cross-tenant access through a forged or reused token.
Add a code challenge to the OAuth2 authorization code flow so a public client like a SPA cannot have its code intercepted, without a client secret.
Apply a write to the UI before the server confirms, roll back on error, and keep the window small so a failed update does not confuse the user.
Pick a rate limit strategy, fixed window, sliding window, or token bucket, and apply it fairly per caller so one client cannot starve the rest.
Deduplicate in-flight requests by key so concurrent callers share one fetch, cache the result, and avoid doubling load when components mount together.
Retry a transient failure with exponential backoff and jitter, cap the attempts, and classify which errors are worth retrying.
Sign JWTs with RS256 using a key pair, rotate keys with a kid header, and publish the public key in a JWKS endpoint for verifiers.
Split auth into a short access token for API calls and a longer refresh in a cookie, so a stolen access token expires fast and refresh is bound to one origin.
Collapse concurrent identical expensive calls into one in-flight work so the result is computed once and shared with all waiters.
Prefetch data on the server and pass it to the client as dehydrated state, so the first paint is full and the client hydrates without a flash of empty content.
Put the session in a signed JWT so the server keeps no session table, enforce expiry and claims, and accept the trade-off that revocation needs a list.
Use SWR to cache, revalidate, and dedupe fetches in React, with a focus on key design and the revalidate-on-focus policy for fresh data.
Use TanStack Query invalidation to refetch only the queries a mutation touches, with query keys as arrays and partial invalidation by prefix.
Test a CLI by invoking its action with argv and a mock stdout, assert the exit code and output, and avoid spawning a process for every case.
Set per-hop timeouts tighter than the caller budget so a slow leaf does not hold the root, and propagate cancellation up the chain.
Keep a bounded revocation list of jti values to force logout before expiry, prune expired entries, and check it on every verify without a session table.
Wire async validators into React Hook Form, debounce server checks, and resolve field errors without blocking the submit button.
Let the browser upload straight to S3 through a presigned URL so your server never proxies the bytes, with a short-lived PUT and a content-type constraint.
Stream multipart uploads straight to storage without buffering in memory, enforce size limits mid-stream, and abort on limit breach.
Report upload progress with XMLHttpRequest upload.onprogress or fetch with a streaming response, and render a percent without re-rendering on every byte.
Adopt Valibot for tree-shakeable schema validation that ships a fraction of Zod bytes while keeping a comparable ergonomic API.
Define the fields, types and guarantees a producer owes its consumers, enforce the contract in tests, and evolve it without breaking downstream jobs.
Retrieve relevant passages with embeddings, store them in a vector index, and ground LLM answers in cited context rather than guesses.
Extract only what changed since the last run with durable watermarks, handle late data, and make reruns idempotent instead of duplicating rows.
Cache model answers by meaning rather than exact text, set a similarity threshold that bounds false hits, and invalidate entries when prompts or models change.
Choose chunk sizes, overlaps and boundaries that keep retrieved passages meaningful, then measure how each strategy affects recall before committing to one.
Compare live feature and prediction distributions against training baselines, choose tests that catch real drift, and alert only when the shift matters.
Constrain model output to a schema, validate every response before trusting it, and repair or retry invalid payloads without looping forever or hiding failures.
Replace subjective impressions with a versioned set of graded examples, task-appropriate metrics and automated regression tests that run on every prompt change.
Set timeouts that match the task, keep partial output useful when a call fails mid stream, and retry only the work that is safe to repeat.
Make a build produce byte-identical output from the same source, so you can verify an artifact was built from the code you reviewed.
Offer HTTP/3 alongside HTTP/2 with the Alt-Svc header, using a compatible port, migration and fallback so clients upgrade safely.
Name spans and label attributes with OpenTelemetry semantic conventions so traces are consistent and queryable across services and languages.
Automate versioning and publishing from commit messages with semantic-release, using conventional commits and CI release pipelines.
Recognise and prevent deadlocks in async code: lock ordering, bounded waits, transaction scope and cancellation so a stall is impossible or fails fast.
Populate a new column over millions of rows in batches, without long locks, replication lag or a table rewrite.
Extract, normalise, chunk and index documents at scale with stable ids, content hashing and incremental updates that avoid full re-indexing.
Serve consistent features to training and inference by separating offline batch computation from an online low-latency store with point-in-time correctness.
Enforce per-client request limits across many instances with an atomic Redis algorithm that survives restarts and clock skew.
Use Bazel for hermetic, incremental JavaScript builds: BUILD targets, the dependency graph, remote caching and correct globals.
Build a publishable library with Rollup: multiple output formats, external peer deps, type declarations and preserving tree shaking.
Understand where DNS is cached, honour TTLs and negative caching, and avoid re-resolving on every request.
Assign levels by what an operator does with the line, keep structured fields, and control volume so logs stay useful and affordable.
Pick between auto-increment, UUID and time-ordered identifiers by weighing index locality, predictability and uniqueness.
Use esbuild for raw speed and Rollup for optimised output, and combine them so fast development does not cost you bundle quality.
Pick the right isolation level by understanding the anomalies each prevents: dirty reads, lost updates, write skew, phantoms and their costs.
Run an incident with a clear commander, a single channel and regular status updates so responders and stakeholders stay aligned.
Wire receivers, processors and exporters into collector pipelines for traces, metrics and logs, with batching, retries and back-pressure.
Describe task dependencies and cache inputs and outputs so a monorepo build skips work that has not changed.
Proxy WebSocket connections correctly: Upgrade headers, timeouts, sticky routing and scale, so ws:// sockets survive the proxy tier.
Sample CPU and memory profiles across a fleet so you can find the code path behind a latency regression without reproducing it.
Keep time-series storage affordable by limiting label combinations, avoiding unbounded dimensions and aggregating high-cardinality data.
Reduce p99 latency by issuing a second request when the first is slow, taking the first response and cancelling the loser.
Turn reliability goals into measurable service level indicators and error budgets that decide when to ship features and when to stop.
Turn monitoring signals into alerts a human can act on, with thresholds from your SLO, grouping, and a runbook per alert.
Measure event loop lag and per-phase time to find the synchronous code that starves I/O, and fix latency spikes that come from your own process.
Catch producer changes before they corrupt downstream tables: compare observed schemas against a pinned contract and quarantine the records that diverge.
Catch typosquatted and malicious dependencies in CI with name-similarity checks, allow-lists, lockfile review and install-script blocking.
Find why a connection pool runs dry, distinguish leaks from slowness, and size and instrument the pool so it recovers.
Find and fix packet loss: read TCP retransmission and RTT signals, distinguish local from path loss, and check queues and MTU.
Find the query that is blocking others, understand which lock mode is held and why, and resolve contention without restarting the database.
Verify that a service and its consumers agree on an API by testing each side against a shared contract instead of a live peer.
Use TLS 1.3 0-RTT early data to cut a round trip on resumed connections, and restrict it to safe requests to avoid replay.
Protect sensitive columns with application-side or pgcrypto encryption, manage keys separately, and understand what encryption breaks.
Measure retrieval quality in a RAG pipeline with recall@k, mean reciprocal rank and hit rate, so you debug retrieval before blaming the generator.
Change published event and queue schemas so old and new consumers keep working during a rolling deploy.
Feed malformed input to parsers automatically so crashes, hangs and wrong-but-accepted output surface before attackers find them.
Produce a software bill of materials for every build so you can answer within minutes whether a new vulnerability affects you.
Use the Expect: 100-continue handshake to avoid uploading a body a server will reject, and implement it correctly on both client and server.
Process out-of-order and late-arriving events with event-time windows, watermarks and allowed lateness so aggregations stay accurate.
Keep a work queue from growing without bound by applying backpressure, priorities and deadlines instead of accepting unlimited tasks.
Build a bounded connection pool with acquire and release, idle reaping, health checks and fair waiting, and understand why pools exhaust.
Build a cache keyed by a hash of its inputs, so identical work is reused and shared across machines, with integrity and safe eviction.
Generate unique ids across many nodes without coordination: UUIDv7, ULID and Snowflake, and the trade-offs of each for storage and indexing.