Error Handling & Structured Logging
Balance errors-as-values vs exceptions in TypeScript, centralize error boundaries, emit JSON logs with correlation IDs, redact secrets/PII, and fail closed.
TL;DR
Use Result<T, E> discriminated unions for expected domain failures and throw for unexpected faults caught at a single error boundary. Emit single-line JSON logs with a correlation_id, redact secrets and PII, and always fail closed when security checks error.
Why it exists
Swallowing exceptions with catch {} hides bugs and can accidentally bypass auth checks (OWASP A10:2025). Meanwhile, console.log("Error:", err) prints multi-line strings that break log parsers and often dumps full req.headers (including Authorization bearer tokens) into third-party log storage.
Mental model
Separate expected business rejections (handled in-band with types) from unexpected crashes (caught once at the boundary, logged with full context, and returned to the caller as a safe, generic error).
Do it
1. Errors as values vs exceptions in TypeScript
throw is invisible in a TypeScript function signature. For expected domain failures (e.g., INSUFFICIENT_FUNDS, EXPIRED_TOKEN), return a discriminated union so the compiler forces the caller to check result.ok:
// Expected domain failures as values; unexpected faults still throw (not run)
export type Result<T, E extends string> =
| { ok: true; value: T }
| { ok: false; error: E; message: string };
export function debitAccount(
balanceCents: number,
amountCents: number,
): Result<number, 'INVALID_AMOUNT' | 'INSUFFICIENT_FUNDS'> {
if (amountCents <= 0) {
return { ok: false, error: 'INVALID_AMOUNT', message: 'Amount must be positive.' };
}
if (balanceCents < amountCents) {
return { ok: false, error: 'INSUFFICIENT_FUNDS', message: 'Balance is too low.' };
}
return { ok: true, value: balanceCents - amountCents };
}2. Error boundaries and failing closed
Put one centralized error boundary at your HTTP framework's top level (or React error.tsx for UI):
- Map known domain
errorcodes to4xxresponses. - Catch unknown exceptions, log them with stack trace +
correlation_id, and return a generic500(application/problem+json) with no internal details. - Fail closed: If an authorization check, rate limiter, or signature verifier throws an unexpected error, deny the request (
403or500)—never fall through tonext().
3. Structured logging & what never to log
Emit single-line JSON to stdout with consistent fields (ts, level, msg, correlation_id, service), and choose levels intentionally: error (broken request/alertable), warn (degraded fallback), info (key lifecycle events), debug (off in prod by default).
Never log credentials, tokens, or raw secrets—see Secrets Management and OWASP Top 10:2025. Configure a redaction allowlist/denylist in your logger (pino redact: ['req.headers.authorization', '*.password', '*.token']) and sanitize log inputs against newline/CRLF injection.
When you DON'T need this
- Tiny CLI scripts or build-time generators: A 30-line script can
throw new Error(...)and print human-readable stderr withoutResultwrappers or JSON log shippers. - Over-wrapping every helper: Don't wrap every
JSON.parseor array lookup inResult<T, E>if the caller can't recover anyway—let truly unexpected bugs bubble to the boundary. - Cost / complexity trade-off:
Resulttypes add minor boilerplate at call sites, and JSON log pipelines cost storage per GB ingested. In exchange, you get exhaustive compiler checks, searchable production logs, and zero leaked stack traces.
Gotchas
catch (err)assumingerris anError: In JavaScript/TypeScript, anything can be thrown (unknown); always normalize witherr instanceof Error ? err : new Error(String(err)).- Swallowing async rejections: Leaving
catch {}empty or forgettingawaitinsidetry/catchsilently drops errors. - Logging entire
reqorenvobjects: Serializingreqoften dumpscookie,authorization, and signed URLs with tokens.
Production checklist
- A single HTTP error boundary catches unhandled errors, logs them once, and returns generic
500problem+json. - Every incoming request gets a
correlation_id(fromX-Request-Idor generated UUID) attached to all logs. - Logger redaction strips
authorization,cookie,password,token, and API keys before writing tostdout. - Security-critical checks (authN, authZ, CSRF, webhook signatures) fail closed on exception.
Check yourself
Check Yourself
1. An authorization middleware throws a Redis timeout error while checking a user's revoked-token list. What does 'fail closed' require?
2. Why should a TypeScript service use Result<T, E> for expected business rejections instead of throwing?
Sources
Related Notes
Zero-Downtime Schema Migrations
Run versioned database migrations safely with expand/contract, batched backfills, immutable migration history, and realistic rollback plans.
Queues & Asynchronous Work
Decouple slow work from HTTP requests with queues vs pub/sub, at-least-once delivery, idempotency keys, exponential backoff retries, and dead-letter queues.