Node.js API Best Practices

Chapter 2 · Practice 4 of 4

Log and exit on uncaught exceptions instead of carrying on

From Validation and error handling

Why it matters

An uncaught exception or unhandled rejection means your process is in an unknown state. Catching it and carrying on can leave half-finished writes, leaked connections or corrupted memory.

The correct response:

  1. Log the error synchronously.
  2. Stop accepting work.
  3. Exit with a non-zero code.
  4. Let your process manager or orchestrator start a fresh instance.

The OWASP Node.js cheat sheet adds one more rule: listen for error events on every EventEmitter and stream you create.

Example

TypeScript
process.on('uncaughtException', (err) => {
  logger.fatal({ err }, 'uncaught exception');
  process.exit(1);
});

process.on('unhandledRejection', (reason) => {
  logger.fatal({ reason }, 'unhandled rejection');
  process.exit(1);
});