AceDevHub
Intermediate Node.js Interview QuestionsIntermediateConcept

Node.js · Question 63

What is the difference between uncaughtException and unhandledRejection?

Direct answer

uncaughtException fires on synchronous throws with no try/catch; unhandledRejection fires when a Promise rejects with no .catch — Node may exit on uncaughtException; treat both as bugs in production, log, graceful shutdown, and use --unhandled-rejections=strict in CI.

These process-level events catch errors that escaped application boundaries — last-resort hooks, not substitutes for handler try/catch.

EventTriggerTypical cause
uncaughtExceptionSync throw outside try/catchJSON.parse in top-level, bug in sync middleware
unhandledRejectionPromise rejected, no handlerMissing await, forgotten .catch on async call
warning (deprecated)Some versions warn before exitFloating promise in background task
  • Do not resume normally — after uncaughtException, process state may be corrupt; shutdown and let PM2/Docker restart.
  • Graceful shutdown — close server, drain connections, then process.exit(1).
  • Framework safety — Fastify catches async route rejections; manual setImmediate async still needs .catch.
process-errors.mjs
process.on("uncaughtException", (err) => {
  console.error("uncaughtException:", err.stack);
  shutdown(1);
});

process.on("unhandledRejection", (reason) => {
  console.error("unhandledRejection:", reason);
  shutdown(1);
});

function shutdown(code) {
  server.close(() => process.exit(code));
  setTimeout(() => process.exit(code), 10_000).unref();
}