惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Node.js Process Crashes: Build a Global Error Boundary That Does Not Panic
The Practica · 2026-05-29 · via The Practical Developer

You wake up to an alert. The API is down. The container restarted six times in the last hour. The logs show nothing but a stack trace from a dependency you did not even know your code touched. The exception was an unhandled promise rejection in a third-party SDK, and because nobody attached a .catch(), the entire Node.js process exited. This is the default behavior since Node.js 15. It is correct, but only if you have done the work to make it survivable.

The real problem is not the crash. It is that most Node.js services do not have a global error strategy. They have try/catch blocks in the happy path, maybe a central error handler in Express, and a prayer that nobody forgets an await. When something slips through, the process exits, the container restarts, and every in-flight request dies with it. If the same exception hits every instance at once (a poison message, a malformed database row, a dependency that changed its error format), your entire fleet restarts in a loop.

This post builds a production-grade global error boundary for Node.js. It catches uncaughtException, unhandledRejection, and async errors that leak past your route handlers. It logs the full context you need to debug the root cause. And it makes an explicit decision for every error class: recover and keep serving, or drain and exit cleanly. No more surprise restarts. No more lost error context.

Why Node.js exits by default, and why that is not the whole story

Before Node.js 15, an unhandled promise rejection printed a deprecation warning and kept going. The promise was silently lost, and your API returned 200 while the actual work failed. This created phantom success states. Node.js 15 changed the default to crash on unhandledRejection. This is safer because it surfaces failures instead of hiding them.

But crashing is not a recovery strategy. It is a last resort. A production server should catch, classify, and handle errors before they reach the process boundary. If an exception is truly unrecoverable (a corrupted module state, a native addon segfault, or a recursive error in the error handler itself), then yes, exit. But most unhandled rejections are recoverable: a network timeout, a schema validation failure, or a missing key in an external API response. These should be logged, metrics should be incremented, and the process should keep serving other requests.

The other trap: even if you register an uncaughtException handler, the process is in an unknown state. The V8 engine does not guarantee that the stack is unwound cleanly, that all resources are released, or that invariants hold. Some engineers therefore say: “always exit after uncaughtException.” That is overly cautious. If you isolate the failure to a single request (for example, an async operation inside an HTTP handler that threw after the response was already sent), the global state is fine. The key is classifying the error, not blanket-exiting.

The three error domains you must handle

Node.js has three separate mechanisms for errors that escape normal control flow.

  1. uncaughtException: A synchronous throw that nobody caught. This fires on the process object.
  2. unhandledRejection: A promise rejection that was not caught with .catch() or try/await.
  3. error events on EventEmitters: If an EventEmitter emits an error event and there is no listener, Node.js throws. The resulting error becomes an uncaughtException.

Plus the async leak: an error thrown inside an Express route handler after res.json() has already been called. Express 4 does not catch errors in async handlers unless you wrap them. An await that rejects after the response is sent becomes an unhandled rejection, even though the route itself is wrapped in a try/catch.

You need handlers for all three domains, and they need to share the same classification and logging logic.

Designing the error boundary

The boundary is a module you require at the top of your entry file, before anything else. It registers the global handlers and attaches a context object to every error so you can trace it back to the original request, user, or job.

The classification rules:

  • Transient errors: Network timeouts, rate limits, temporary unavailability. Log, emit a metric, keep serving.
  • Operational errors: Validation failures, missing resources, bad input. These are expected. Log at warn, return the right HTTP status, keep serving.
  • Programming errors: Null pointer exceptions, type errors, assertion failures. These are bugs. Log at error with a full stack trace, keep serving if the stack is isolated to one request, exit after a drain period if the error happens during startup or in a singleton module.
  • Fatal errors: Native addon crashes, recursive errors in the error handler, out-of-memory conditions caught too late. Log, set a terminating flag, start a graceful shutdown.

Here is the core boundary module.

The global error boundary implementation

// error-boundary.ts
import { EventEmitter } from 'node:events';
import os from 'node:os';

interface ErrorContext {
  requestId?: string;
  userId?: string;
  route?: string;
  jobId?: string;
  [key: string]: unknown;
}

interface BoundaryOptions {
  onFatal?: (error: Error, context?: ErrorContext) => void;
  onError?: (error: Error, context?: ErrorContext) => void;
  gracefulShutdown?: (code?: number) => Promise<void>;
  maxRestarts?: number; // for cluster mode
}

let isShuttingDown = false;
const activeContexts = new WeakMap<Error, ErrorContext>();

export function setErrorContext(error: Error, context: ErrorContext): void {
  activeContexts.set(error, context);
}

function getContext(error: Error): ErrorContext {
  return activeContexts.get(error) || {};
}

function classifyError(error: Error): 'transient' | 'operational' | 'programming' | 'fatal' {
  if (error.message.includes('ECONNREFUSED') || error.message.includes('ETIMEDOUT')) {
    return 'transient';
  }
  if (error.message.includes('ECONNRESET') || error.message.includes('EPIPE')) {
    return 'transient';
  }
  if (error.name === 'ValidationError' || error.name === 'NotFoundError') {
    return 'operational';
  }
  if (error.name === 'TypeError' || error.name === 'ReferenceError' || error.name === 'AssertionError') {
    return 'programming';
  }
  if (error.name === 'RangeError' && error.message.includes('Maximum call stack')) {
    return 'fatal';
  }
  return 'programming';
}

function logError(error: Error, classification: string, context: ErrorContext): void {
  const logLine = {
    level: classification === 'fatal' ? 'fatal' : classification === 'programming' ? 'error' : 'warn',
    event: 'global_error_boundary',
    classification,
    errorName: error.name,
    errorMessage: error.message,
    stack: error.stack?.split('\n').slice(0, 8),
    context,
    pid: process.pid,
    hostname: os.hostname(),
    timestamp: new Date().toISOString(),
  };
  console.error(JSON.stringify(logLine));
}

export function installErrorBoundary(options: BoundaryOptions = {}): void {
  process.on('uncaughtException', (error: Error) => {
    if (isShuttingDown) {
      logError(error, 'fatal', { shutdownInProgress: true });
      process.exit(1);
    }

    const classification = classifyError(error);
    const context = getContext(error);
    logError(error, classification, context);

    if (classification === 'fatal') {
      isShuttingDown = true;
      options.onFatal?.(error, context);
      options.gracefulShutdown?.(1).finally(() => process.exit(1));
      return;
    }

    options.onError?.(error, context);
  });

  process.on('unhandledRejection', (reason: unknown) => {
    const error = reason instanceof Error ? reason : new Error(String(reason));

    if (isShuttingDown) {
      logError(error, 'fatal', { shutdownInProgress: true });
      process.exit(1);
    }

    const classification = classifyError(error);
    const context = getContext(error);
    logError(error, classification, context);

    if (classification === 'fatal') {
      isShuttingDown = true;
      options.onFatal?.(error, context);
      options.gracefulShutdown?.(1).finally(() => process.exit(1));
      return;
    }

    options.onError?.(error, context);
  });

  // Prevent EventEmitter 'error' events from crashing the process.
  // Attach a default listener to the prototype so *all* emitters get it.
  const originalEmit = EventEmitter.prototype.emit;
  EventEmitter.prototype.emit = function (event: string | symbol, ...args: unknown[]) {
    if (event === 'error') {
      const error = args[0] instanceof Error ? args[0] : new Error(String(args[0]));
      const hasListener = this.listenerCount('error') > 0;
      if (!hasListener) {
        // This would have become an uncaughtException. Route it through the boundary.
        const classification = classifyError(error);
        const context = getContext(error);
        logError(error, classification, context);
        if (classification === 'fatal') {
          isShuttingDown = true;
          options.onFatal?.(error, context);
          options.gracefulShutdown?.(1).finally(() => process.exit(1));
        } else {
          options.onError?.(error, context);
        }
        return false;
      }
    }
    return originalEmit.call(this, event, ...args);
  };
}

Install it before your server starts:

// main.ts
import { installErrorBoundary } from './error-boundary';

installErrorBoundary({
  onFatal: (error, context) => {
    // Send to PagerDuty, Sentry, or your alerting channel
    console.error(`FATAL ERROR on ${context.route || 'unknown'}. Initiating shutdown.`);
  },
  onError: (error, context) => {
    // Increment a Prometheus counter or StatsD metric
    console.error(`RECOVERABLE ERROR on ${context.route || 'unknown'}. Continuing.`);
  },
  gracefulShutdown: async (code = 1) => {
    // Close server, drain connections, close database pool
    console.error('Starting graceful shutdown...');
    await new Promise((resolve) => setTimeout(resolve, 5000));
    console.error('Graceful shutdown complete.');
  },
});

// Now import everything else
import { startServer } from './server';
startServer();

The installErrorBoundary call must be the first thing in your entry file. If an error happens during module loading (a syntax error in a config file, a missing environment variable), the boundary is already in place.

Attaching context to errors

A stack trace without context is a puzzle. You need to know which request, which user, which job triggered the failure. The boundary uses a WeakMap so you can attach context to any error object before it escapes.

Inside your request handler, wrap the async work and attach context:

import { setErrorContext } from './error-boundary';

app.get('/api/orders/:id', async (req, res, next) => {
  try {
    const order = await fetchOrder(req.params.id);
    res.json(order);
  } catch (error) {
    if (error instanceof Error) {
      setErrorContext(error, {
        requestId: req.id,
        userId: req.user?.id,
        route: 'GET /api/orders/:id',
        orderId: req.params.id,
      });
    }
    next(error);
  }
});

The context is picked up in the global handler and included in the JSON log line. If the error escapes the route handler and becomes an unhandled rejection, the context is still attached. Without this, a TypeError: Cannot read property 'name' of undefined is a needle in a haystack. With it, you know the exact route and request ID where it happened.

For background jobs, attach the job name and arguments:

async function processEmailJob(job: Job) {
  try {
    await sendEmail(job.data);
  } catch (error) {
    if (error instanceof Error) {
      setErrorContext(error, {
        jobId: job.id,
        jobName: 'send-email',
        recipient: job.data.to,
      });
    }
    throw error; // let the worker's retry logic handle it
  }
}

The EventEmitter trap and why you must patch emit

Every readable stream, every database connection, every HTTP client in Node.js is an EventEmitter. If an emitter emits an error event and nobody is listening, Node.js throws that error synchronously, and it becomes an uncaughtException. This is a common source of surprise crashes.

// This crashes the process if the stream errors after 'data' finishes.
const stream = fs.createReadStream('file.txt');
stream.on('data', (chunk) => console.log(chunk));
// Forgot stream.on('error', ...)

The boundary patches EventEmitter.prototype.emit so that error events without a listener are routed through the boundary instead of crashing the process. This is a global change, which is why it belongs in the boundary module. Every emitter in your process now gets a default error listener.

This does not suppress errors. It logs them, classifies them, and either continues or shuts down gracefully. You still want explicit error listeners on your streams and connections because explicit handling is better. The patch is a safety net.

Handling errors in async route handlers

Express 4 does not catch rejected promises in route handlers. You must wrap async handlers or use a utility:

function asyncHandler(fn: RequestHandler) {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
}

app.get('/api/orders/:id', asyncHandler(async (req, res) => {
  const order = await fetchOrder(req.params.id);
  res.json(order);
}));

With asyncHandler, a rejected promise calls next(error), which Express routes to your central error middleware. But if the error throws after the response has been sent (for example, a logging call that rejects), Express has already moved on. That rejection becomes an unhandled rejection, and this is where the global boundary catches it.

The lesson: async handlers are not enough. You need both per-request error handling (for errors during the request) and global error handling (for errors that leak afterward).

The classification logic in practice

The classifyError function in the boundary is where your domain knowledge lives. The example above uses name and message strings, which is a starting point. In a real codebase, you should classify by error constructor:

function classifyError(error: Error): string {
  if (error instanceof ValidationError) return 'operational';
  if (error instanceof DatabaseTimeoutError) return 'transient';
  if (error instanceof TypeError) return 'programming';
  if (error instanceof RangeError) return 'fatal';
  // ... and so on
  return 'programming';
}

The classification decides whether the process lives or dies. Transient errors should never crash the server. Programming errors might indicate a bug, but if they are isolated to a single request, the process state is fine. Fatal errors are the only ones that should trigger shutdown. That list should be short: OOM conditions, stack overflow, recursive errors in the boundary itself.

Metrics and alerting

The boundary should emit metrics, not just logs. For every caught error, increment a counter tagged with classification and error name:

// Inside onError
metricsCounter.inc({
  name: 'global_error_boundary',
  classification,
  error_name: error.name,
});

Alert rules:

  • Transient errors above 10 per minute: investigate the downstream service.
  • Programming errors above 1 per minute: there is a bug in the code path. Check the logs.
  • Any fatal error: page immediately. The process is shutting down.
  • Unhandled rejections above 5 per minute: review the codebase for missing await or .catch().

The graceful shutdown handler

The shutdown handler should not be a process.exit() call. It should drain in-flight requests, close the server, flush logs, and then exit. Here is a robust implementation:

async function gracefulShutdown(code = 0): Promise<void> {
  console.log(JSON.stringify({ event: 'shutdown_start', code, timestamp: new Date().toISOString() }));

  if (server) {
    await new Promise<void>((resolve) => {
      server.close(resolve);
      // Force close after 10 seconds
      setTimeout(() => resolve(), 10_000);
    });
  }

  if (dbPool) {
    await dbPool.end();
  }

  if (logger) {
    await logger.flush();
  }

  console.log(JSON.stringify({ event: 'shutdown_complete', code, timestamp: new Date().toISOString() }));
  process.exit(code);
}

The key detail: server.close() stops accepting new connections but waits for existing HTTP requests to finish. The 10-second timeout prevents a hung request from keeping the process alive forever.

Testing the boundary

You should test that the boundary actually catches errors. In a test file, spawn a child process that throws each error type and assert the exit code:

import { spawn } from 'node:child_process';
import { describe, it } from 'node:test';
import assert from 'node:assert';

describe('error boundary', () => {
  it('keeps the process alive after a transient error', async () => {
    const child = spawn('node', ['-e', `
      require('./error-boundary').installErrorBoundary();
      setTimeout(() => {
        const err = new Error('ECONNREFUSED');
        throw err;
      }, 100);
      setTimeout(() => process.exit(0), 500);
    `]);

    const exitCode = await new Promise<number>((resolve) => child.on('exit', resolve));
    assert.strictEqual(exitCode, 0);
  });

  it('exits after a fatal error', async () => {
    const child = spawn('node', ['-e', `
      require('./error-boundary').installErrorBoundary();
      setTimeout(() => {
        const err = new RangeError('Maximum call stack size exceeded');
        throw err;
      }, 100);
    `]);

    const exitCode = await new Promise<number>((resolve) => child.on('exit', resolve));
    assert.strictEqual(exitCode, 1);
  });
});

These tests run in seconds and verify that your classification logic does what you think it does.

What to avoid

Do not swallow all errors and continue. If a TypeError keeps firing from the same module, your process may be in an inconsistent state. The boundary logs and continues, but you should alert on programming errors and treat a sustained rate as a deploy-blocking bug.

Do not log at info or debug for errors. Errors are always warn or above. A boundary that logs at info trains your team to ignore it.

Do not rely on domain module. It is deprecated. It was an earlier attempt at isolating errors to specific contexts, but its behavior with async/await was unpredictable. The approach in this post (WeakMap context + classification) replaces it with something explicit and testable.

Practical takeaway

A Node.js process without a global error boundary is a time bomb. The default behavior (exit on unhandled rejection) is correct for scripts, but dangerous for long-running servers because it turns every missing .catch() into a potential outage.

Add the boundary as the first line of your entry file. Classify errors into transient, operational, programming, and fatal. Attach request context to every error so you can trace it. Log structured JSON so your aggregator can alert on patterns. Emit metrics so you can see trends. Handle graceful shutdown so in-flight requests are not dropped. And test the boundary like any other critical code path.

The 2 AM alert should tell you exactly what failed, where, and why. It should not be a blank restart loop with no stack trace and no idea where to start.


A note from Yojji

Production-hardened Node.js services need more than feature shipping. They need defensive error handling that turns surprise crashes into classified, observable events with clear resolution paths. Yojji builds backend systems with exactly that level of operational maturity, from global error boundaries to distributed tracing across microservices.

Yojji is an international custom software development company founded in 2016, with offices in Europe, the US, and the UK. Their 50+ engineers specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, Google Cloud), and scalable microservices architecture. If your team is moving from prototype to production and needs the kind of reliability that survives a 2 AM exception, Yojji is worth a conversation.