Error Handling Patterns for Production Applications
Classify errors, propagate them with context, log and trace them without leaking secrets, and design recovery paths that keep production running.
On this page
Introduction
Error handling is the part of the codebase where production experience is won or lost. The application that distinguishes a transient network blip from a permanent programming bug, that logs enough context to diagnose a failure at 3 a.m. without leaking the user’s password, and that degrades gracefully instead of returning a 500 to every request is the application that stays up. The application that catches everything with try { ... } catch (e) { console.log(e) } is the one that swallows the signal of a failing database until the database is down entirely. This article covers the patterns that make error handling a first-class engineering concern rather than an afterthought: error classification, propagation with context, structured logging, and recovery.
Classify Before You Handle
Not all errors are the same, and handling them the same way is a bug. A 404 from a downstream API is not an error you retry — the resource does not exist. A 503 is. A TypeError from a null dereference is a programming bug that should crash the request and alert a human; a ECONNRESET is a transient infrastructure failure that should retry. The first step in a robust error strategy is a taxonomy.
class AppError extends Error {
constructor(message: string, public readonly kind: string, public readonly retryable: boolean, public readonly statusCode: number, public readonly context?: Record<string, unknown>) {
super(message);
this.name = this.constructor.name;
}
}
class ValidationError extends AppError {
constructor(message: string, context?: Record<string, unknown>) { super(message, "validation", false, 422, context); }
}
class NotFoundError extends AppError {
constructor(resource: string, id: string) { super(`${resource} not found`, "not_found", false, 404, { resource, id }); }
}
class TransientError extends AppError {
constructor(message: string, context?: Record<string, unknown>) { super(message, "transient", true, 503, context); }
}
class ConfigurationError extends AppError {
constructor(message: string) { super(message, "configuration", false, 500); }
}
The retryable flag is the contract between the error and the retry layer: a transient error is retried, a validation error is not. The statusCode is the contract between the error and the HTTP layer. The kind is the contract between the error and the observability layer, so you can slice error rates by category in your dashboard. This taxonomy is the foundation; every other pattern builds on it.
Propagation with Context
An error that says “connection refused” is nearly useless; an error that says “connection refused while fetching user 42 from the billing service at retry 2 of 4” is a diagnosis. The pattern is to wrap errors as they propagate up the stack, adding the context each layer knows, without losing the original cause. In Go this is fmt.Errorf("fetching user %d: %w", id, err); in JavaScript it is a custom error that carries a cause.
class WrappedError extends Error {
constructor(message: string, public readonly cause: unknown, public readonly context?: Record<string, unknown>) {
super(message);
this.name = "WrappedError";
}
}
async function getUser(id: string) {
try {
const res = await fetch(`/billing/users/${id}`, { signal: AbortSignal.timeout(2000) });
if (!res.ok) throw new AppError(`billing returned ${res.status}`, "http", res.status >= 500, res.status, { id });
return await res.json();
} catch (err) {
throw new WrappedError("fetching user from billing", err, { id, service: "billing" });
}
}
The cause chain preserves the root error and its stack; the context accumulates the identifiers each layer adds. When the error reaches the top-level handler, you can walk the chain to produce a single log entry with the full story. Never discard the original error by catching and throwing a new message alone — the stack trace of the original is the most valuable diagnostic you have.
The Top-Level Handler: Log, Respond, Exit
There is exactly one place that should catch every error: the top-level handler at the edge of the request. In an Express app this is the error-handling middleware registered last; in a worker it is the wrapper around each job. This handler does three things: it logs the error with full context, it translates the error into an appropriate HTTP response, and it ensures no secret or internal detail leaks to the client.
function errorHandler(err: unknown, req: Request, res: Response, next: NextFunction) {
const appErr = err instanceof AppError ? err : new AppError("unexpected error", "internal", false, 500);
const logEntry = {
level: appErr.statusCode >= 500 ? "error" : "warn",
message: err instanceof Error ? err.message : String(err),
kind: appErr.kind,
statusCode: appErr.statusCode,
requestId: req.id,
userId: req.user?.id,
path: req.path,
context: appErr.context,
stack: appErr.statusCode >= 500 ? (err instanceof Error ? err.stack : undefined) : undefined,
};
logger.log(logEntry);
res.status(appErr.statusCode).json({
error: clientMessage(appErr),
requestId: req.id,
});
}
function clientMessage(err: AppError): string {
// Never expose internal details for 5xx; the client cannot act on them.
if (err.statusCode >= 500) return "Something went wrong. We have been notified.";
return err.message;
}
The stack trace is logged only for 5xx errors — a 422 validation error does not need a stack, and logging stacks for every client error floods your log aggregator. The client message for a 5xx is generic; the detailed message is in the log, keyed by requestId, which the client receives so support can correlate. Never put a secret, a SQL query, or an internal path in a client-facing error message.
Structured Logging and the Redaction Layer
Logs are the primary diagnostic in production, and unstructured console.log is nearly useless in a distributed system where a thousand requests are in flight. Log structured JSON with a timestamp, a level, a request id, and the context object, so your aggregator can filter and correlate. Pair the logger with a redaction layer that strips known sensitive keys (password, authorization, token, creditCard) from every log entry before it is written, so a careless logger.info({ user }) does not leak the user’s password hash into your log store.
const SENSITIVE = new Set(["password", "authorization", "token", "secret", "cookie"]);
function redact(obj: unknown): unknown {
if (typeof obj !== "object" || obj === null) return obj;
return Object.fromEntries(Object.entries(obj as Record<string, unknown>).map(([k, v]) =>
[k, SENSITIVE.has(k.toLowerCase()) ? "[redacted]" : redact(v)]
));
}
Log at the right level. error is for something a human must investigate (a 5xx, a failed database connection). warn is for something unexpected but handled (a retry that eventually succeeded, a deprecated API call). info is for normal operation. debug is for development. A log store full of info is a log store where the error entries are hard to find; tune the levels so the signal stands out.
Recovery and Degradation
The best error handling is the handling that keeps the feature working. When the recommendations service is down, the product page should render without recommendations rather than 500. When the search index is unavailable, the site should fall back to a database search rather than fail. Design every external dependency with a fallback: a cached response, a default value, a degraded path. The circuit breaker from the resilience patterns article is the mechanism that decides when to stop trying and use the fallback.
async function getProductPage(id: string) {
const product = await getProduct(id); // required; if this fails, the page fails
let recommendations: Product[] = [];
try {
recommendations = await recommendationsService.get(id);
} catch (err) {
logger.warn({ msg: "recommendations failed, rendering without", id, err: toLoggable(err) });
recommendations = await cache.get(`recs:${id}`) ?? []; // stale cache or empty
}
return { product, recommendations };
}
The pattern is to distinguish required dependencies (the product fetch; without it the page cannot render) from enhancing dependencies (the recommendations; the page is useful without them). Required failures propagate; enhancing failures are caught, logged, and degraded. The user never sees a broken page because a non-essential service had a hiccup.
Error Boundaries in UIs and Error Budgets for Alerting
The error-handling patterns above are server-side, but the user interacts with a UI, and the UI needs its own error boundary. In React, an error boundary is a component that catches errors thrown by its children during render and shows a fallback instead of a blank screen. Without one, a render error in a single component unmounts the entire tree — the user sees a white page and the only recovery is a refresh. An error boundary around each route (or each major region) confines the failure to the region that broke, so a bug in the recommendations panel does not take the product page with it.
class ErrorBoundary extends React.Component<{ fallback: React.ReactNode; children: React.ReactNode }, { error: Error | null }> {
state = { error: null as Error | null };
static getDerivedStateFromError(error: Error) { return { error }; }
componentDidCatch(error: Error, info: React.ErrorInfo) {
logger.error({ msg: "UI render error", error: toLoggable(error), componentStack: info.componentStack });
}
render() {
return this.state.error ? this.props.fallback : this.props.children;
}
}
// Wrap each route so a failure is confined.
<ErrorBoundary fallback={<RegionError onRetry={() => location.reload()} />}>
<ProductPage />
</ErrorBoundary>
The fallback should offer a recovery path — a retry that re-mounts the boundary, a link to the home page, or a contact-support link — not just “something went wrong.” Log the error with the component stack, which localizes the failure to the component that threw, and distinguish a render error (caught by the boundary) from an event-handler error (not caught, because it happens outside render) by wrapping event handlers in try/catch with the same logging. The boundary is the UI’s analog of the server’s top-level handler: the one place that catches everything and degrades gracefully.
Error budgets are the mechanism that turns error handling from a reactive fire drill into a proactive engineering discipline. An error budget is the rate of errors a service is allowed to incur over a window — say, 1% of requests over 30 days — and it is the shared currency between the reliability goal and the velocity goal. When the error rate is well under budget, the team can deploy aggressively, because there is reliability headroom to absorb a regression. When the error rate is consuming the budget, deploys slow down and the focus shifts to reliability. When the budget is exhausted, deploys freeze until the error rate recovers.
// Compute the error budget burn rate from metrics.
async function burnRate(service: string, window: string): Promise<number> {
const errors = await metrics.count({ service, status: "5xx", window });
const total = await metrics.count({ service, window });
const observedRate = errors / total;
const budgetRate = 0.01; // 1% SLO
return observedRate / budgetRate; // 1.0 = consuming at exactly the budget rate
}
// burnRate > 1 for a sustained window -> freeze deploys; > 14 over 1h -> page.
The burn rate is the ratio of the observed error rate to the budgeted rate: a burn rate of 2 means you are consuming the budget twice as fast as allowed, and you will exhaust it in half the window. Alert on a fast burn (a high rate over a short window, which indicates an acute regression) and a slow burn (a moderate rate over a long window, which indicates chronic drift). The fast burn pages; the slow burn creates a ticket. This multi-window alerting catches both the sudden outage and the gradual degradation that erodes the budget over weeks, and it does so without a single threshold that fires on every spike.
The error budget reframes the relationship between deploys and reliability: a regression is not a violation to be punished but a withdrawal from a shared account, and the account is replenished by good behavior over time. This makes the trade-off explicit and data-driven rather than political, and it gives the team a principled answer to “should we deploy on Friday” — yes, if the budget has headroom; no, if it does not.
Conclusion
Production-grade error handling rests on a taxonomy that classifies errors by kind, retryability, and status; propagation that wraps errors with context while preserving the cause; a single top-level handler that logs with structure and redaction and responds with safe, correlated messages; and recovery paths that degrade enhancing features instead of failing the whole request. The discipline is to handle errors at the right layer — classify and wrap deep in the stack, log and respond at the edge, and design fallbacks for every non-essential dependency. Done well, error handling is invisible to the user and invaluable to the operator.
Report a problem with this articleOpens a pre-filled issue on GitHub.