The Practical Developer

Node.js Process Crashes: Build a Global Error Boundary That Does Not Panic

A single unhandled promise rejection took down your Node.js server at 2 AM. Here is how to build a global error boundary that catches uncaught exceptions, unhandled rejections, and async failures, logs actionable context, and keeps the process alive or exits cleanly without losing the trail.

Lines of code illuminated on a dark screen, with a single red error line breaking the flow, representing the moment a global error boundary intercepts a fatal failure

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.