Lesson 22 / 28
Uncaught Exceptions & Process Events
The last line of defense when something escapes every catch.
uncaughtException
Listen for exceptions that escape all your try/catch blocks — use it to log and exit cleanly, not to keep running.
process.on("uncaughtException", (err) => {
console.error("Fatal error:", err);
process.exit(1);
});
process.on("unhandledRejection", (reason) => {
console.error("Unhandled rejection:", reason);
process.exit(1);
});The exit event
process.on("exit", ...) fires right before Node shuts down — good for final synchronous cleanup, but no async work runs there.
Quick check: Once uncaughtException fires, what's the recommended action?
- Ignore it and continue
- Log it and exit the process
- Retry the failed operation automatically
Answer
Log it and exit the process — After an uncaught exception, app state may be corrupted — log the error and exit rather than limping along.