tezvyn:

Node.js Uncaught Exceptions: Clean Up, Don't Continue

AI-drafted, machine-checkedSource: nodejs.orgadvanced

An uncaught exception is a fire alarm for your Node.js app, signaling an unknown state. Use the `process.on('uncaughtException')` hook for last-resort synchronous cleanup before exiting, not to resume normal operation.

WHY IT EXISTS An uncaught exception means an error has occurred that was not handled anywhere in your application. Node.js provides the 'uncaughtException' event to give a developer one last chance to perform synchronous, cleanup actions before the process terminates, preventing an abrupt crash that might leave resources in a bad state.

THE MENTAL MODEL Treat an uncaught exception like a fire alarm in a factory. The machinery (your application) is now in an unknown, potentially dangerous state. You don't try to fix the machine and resume production; you evacuate the building (exit the process). The 'uncaughtException' handler is your brief window to grab the emergency logbook and shut off the main gas line on your way out. It is not a global try...catch block.

HOW IT WORKS When an error is thrown but not caught by any try...catch block or promise .catch() handler, it propagates up to the event loop. The event loop then emits an 'uncaughtException' event on the global 'process' object. You can listen for it with process.on('uncaughtException', (err, origin) => { ... }). The code in your listener must be synchronous. After your listener code runs, the process will exit unless you've configured it otherwise, which is not recommended.

WHEN TO USE IT The only correct use is for synchronous, last-resort cleanup. This includes actions like writing a crash report to a file, sending a final error metric to a monitoring service, or closing critical database connections. The goal is to gather as much diagnostic information as possible and leave external systems in a consistent state before the process dies.

WHEN NOT TO USE IT Never use it to resume application flow. Attempting to continue running after an uncaught exception is extremely dangerous. The application's state is corrupted, memory may be inconsistent, and further operations could lead to data loss, security holes, or even more cryptic errors. It is not a substitute for proper, localized error handling throughout your codebase.

ONE CANONICAL EXAMPLE This example shows logging the error and then explicitly exiting, which is the correct and safe pattern.

process.on('uncaughtException', (err, origin) => { console.error(Caught exception: {err}\nException origin: {origin}); // Perform synchronous cleanup, like writing a crash log. // Then, ensure the process exits with a non-zero code. process.exit(1); });

// This code will trigger the handler after 1 second. setTimeout(() => { throw new Error('This will crash the application safely!'); }, 1000);

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.