Engineering Express Error Handling Observability

Express Error Handling and Observability: No Silent Failures in Production

9 min readWANOVA

A production error you only discover when a user complains is the nightmare scenario. By the time someone files a ticket, the problem has already affected dozens or hundreds of users, the context has evaporated, and you are debugging blind. Good observability inverts this: you know about the error before most users encounter it, you have the full request context and stack trace, and you know precisely how many users were affected and when it started. Building this observability stack is not complicated — but it requires deliberate setup of structured logging, error tracking, health checks, and alerting. This guide covers exactly how we build it at WANOVA.

Error Classification: The Foundation of Good Error Handling

Not all errors deserve the same response. An error handling system that treats a validation error the same as a database connection failure will either over-alert (noise that gets ignored) or under-alert (real problems missed). Clear error classification is the first step toward an error handling system that is both reliable and actionable.

  • Operational errors: invalid request, 404, validation failure — expected and handled
  • Programmer errors: null reference, type error, logic bug — must be fixed immediately
  • Third-party errors: DB connection, external API failure — needs retry/fallback
  • Unhandled rejections: Promise.reject() without catch — most dangerous because they're silent
  • Rule: operational errors → respond with appropriate error response, programmer errors → log + alert + investigate
  • AppError class: extend Error with statusCode and isOperational fields — makes classification automatic
  • Zod validation errors: treat as operational — parse and return field-level error details
  • Database connection errors: treat as third-party — retry with backoff, circuit break after threshold

Centralized Error Middleware in Express

Express error middleware with 4 parameters (err, req, res, next) catches all errors thrown or passed to next() anywhere in the application. Having a single centralized handler means consistent error responses, consistent logging, and a single place to update error handling behavior. Without it, each route handles errors independently — leading to inconsistent response formats and missed logging.

  • Check error type: is it an AppError (operational) or an unexpected Error?
  • Respond with correct status code: 400 for validation, 401 for auth, 404, 500
  • Return structured JSON: { error: { code, message, details } }
  • In production: don't return stack traces to the client — send them to Sentry only
  • process.on('unhandledRejection') + process.on('uncaughtException') as a last line of defense
  • Async error propagation: wrap async route handlers with a utility that catches and calls next(err)
  • Error normalization: convert Zod errors, Drizzle errors, and JWT errors into AppError format
  • Rate limit errors: 429 status with Retry-After header — treat as operational

Structured Logging with Pino

console.log statements in production create log lines that are impossible to search, aggregate, or analyze. Pino generates JSON log lines with consistent structure — every log entry has a timestamp, log level, request ID, and any additional context you add. This structure makes logs searchable in Datadog, Grafana Loki, or any log management tool, enabling queries like 'all errors for user X in the last hour'.

  • pino-http middleware: automatically logs every request with status, method, latency
  • req.log.info({ userId, action }) instead of console.log
  • Child loggers: req.log.child({ requestId }) to track each request
  • Log levels: trace, debug, info, warn, error, fatal — use the right one
  • pino-pretty for development, raw JSON for production where tools like Datadog analyze it
  • Sensitive data: never log passwords, tokens, or PII — use Pino's redact option
  • Log sampling: trace level in production causes massive log volume — sample at 1% for trace
  • Structured error logging: log err.message, err.code, err.stack — not just the error object
→ Pino is 5-10x faster than winston — important in high-traffic APIs where logging itself can slow the application.

Sentry: Automatic Error Tracking with Full Context

Sentry captures every unhandled error with its full context: stack trace, request URL, headers, user identity, and custom breadcrumbs showing what happened before the error. This context is the difference between debugging taking 2 minutes or 2 hours. Sentry also tracks error frequency, so you can distinguish a new regression from a pre-existing rare error.

  • @sentry/node: automatically captures every unhandled exception with stack trace
  • Request context: Sentry adds request URL, headers, user info to every error
  • Performance monitoring: track latency per endpoint and database
  • Alerts: Slack/email notification on new errors or rising error rates
  • Release tracking: link errors to deploy version — which deploy started this error?
  • User identity: Sentry.setUser({ id, email }) — know which users are experiencing errors
  • Custom breadcrumbs: Sentry.addBreadcrumb() adds structured events leading to the error
  • Sampling rate: 100% for errors, 10% for transactions in production — balances cost and coverage

Health Checks: Your Service's Heartbeat

A health check endpoint gives your infrastructure — load balancers, orchestration platforms, and uptime monitors — a signal about whether the service is ready to handle traffic. A good health check distinguishes between liveness (is the process alive?) and readiness (is the process ready to serve requests, with DB and Redis connections established?). This distinction is critical: you want to restart dead processes but not pull healthy-but-busy ones from the load balancer.

  • GET /api/health: checks DB connection, Redis, external services
  • Liveness check: is the process alive? — simple page returning 200
  • Readiness check: is the app ready to receive traffic? — checks DB and others
  • Uptime Robot or Better Stack: hits /health every minute and alerts you on failure
  • Add version: commit hash in the response — know which version is in production
  • Dependency timeout: health check dependency calls must have short timeouts — 500ms max
  • Degraded state: return 200 with status 'degraded' when optional services are down
  • Health check caching: cache the check result for 5 seconds to avoid DB load from frequent probes

Complete Production Observability Patterns

The following patterns form the production observability baseline that every Express application should have before going live. Together they create a system where no failure is silent: every error is captured, every slow request is tracked, and every system state change generates a signal that reaches the right person before users notice.

  • Correlation ID: add X-Request-ID to every request — links multiple logs for the same request
  • Graceful shutdown: listen for SIGTERM, complete current requests then close
  • Circuit Breaker: if an external API fails 5 times in a row, stop calling it for 60 seconds
  • Timeout on all I/O: DB queries, HTTP requests — never wait indefinitely
  • Alerting rules: > 10 500 errors/minute → wake up on-call at any time
  • SLO tracking: define p95 latency and error rate targets — alert when SLO is at risk
  • Runbook links: include a runbook URL in alert messages — reduce time-to-resolution
  • Post-mortem discipline: every SEV1 incident gets a blameless post-mortem within 48 hours

OpenTelemetry: Vendor-Neutral Distributed Tracing

OpenTelemetry is the open standard for distributed tracing, metrics, and logs. Instrumenting your Express application with OpenTelemetry provides request traces that span multiple services, showing exactly where time is spent across database queries, external API calls, and internal function calls. Unlike vendor-specific SDKs, OpenTelemetry lets you switch between Jaeger, Grafana Tempo, Datadog, and Honeycomb without changing your instrumentation code.

  • @opentelemetry/sdk-node: the Node.js SDK with auto-instrumentation
  • Auto-instrumentation: automatically traces HTTP requests, pg queries, Redis, and more
  • Custom spans: opentelemetry.trace.getActiveSpan().addEvent() for important operations
  • Trace propagation: W3C TraceContext header links traces across service boundaries
  • Sampling: head-based sampling at 10% for normal traffic, 100% for errors
  • Grafana Tempo + Prometheus: open-source tracing and metrics without per-seat pricing
  • Connecting logs to traces: inject traceId into Pino log lines — correlate logs with traces

Free 30-minute consultation

Get an initial concept for your platform.

شعار وانوفا WANOVA

Built for the future. Premium digital platforms and cinematic software solutions.

Quick Links

© 2026 WANOVA. All rights reserved.