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.
| Event | Trigger | Typical cause |
|---|---|---|
| uncaughtException | Sync throw outside try/catch | JSON.parse in top-level, bug in sync middleware |
| unhandledRejection | Promise rejected, no handler | Missing await, forgotten .catch on async call |
| warning (deprecated) | Some versions warn before exit | Floating 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();
}