Skip to content

Handle Uncaught Errors Safely

Log unhandled promise rejections and uncaught exceptions so a process does not fail silently, then exit after an uncaught exception.

Language: Node.js

Added on: 21st August 2026

process.on("unhandledRejection", (err) => {
  console.error("Unhandled rejection:", err);
});

process.on("uncaughtException", (err) => {
  console.error("Uncaught exception:", err);
  process.exit(1);
});

Caveats

Register these listeners at startup. After uncaughtException the process is in an unknown state, so this exits rather than continuing. unhandledRejection does not exit; add process.exit(1) there too if you want the same policy.