0
0
NodejsDebug / FixBeginner · 4 min read

How to Handle Uncaught Exceptions in Node.js Safely

In Node.js, you can handle uncaught exceptions by listening to the process.on('uncaughtException') event. This lets you log the error and perform cleanup before safely shutting down the app to avoid unexpected crashes.
🔍

Why This Happens

An uncaught exception occurs when your Node.js program throws an error that is not caught by any try-catch block or error handler. This causes the Node.js process to crash immediately, which can stop your application unexpectedly.

javascript
setTimeout(() => {
  // This error is not caught anywhere
  throw new Error('Something went wrong!');
}, 1000);
Output
node:internal/process/promises:288 triggerUncaughtException(err, true /* fromPromise */); ^ Error: Something went wrong! at Timeout._onTimeout (path/to/file.js:3:9) at listOnTimeout (node:internal/timers:564:17) at processTimers (node:internal/timers:507:7)
🔧

The Fix

To handle uncaught exceptions, add a listener to the process object for the uncaughtException event. This allows you to log the error and perform any cleanup before exiting the process gracefully.

javascript
process.on('uncaughtException', (err) => {
  console.error('Uncaught Exception caught:', err.message);
  // Perform cleanup here if needed
  process.exit(1); // Exit with failure code
});

setTimeout(() => {
  throw new Error('Something went wrong!');
}, 1000);
Output
Uncaught Exception caught: Something went wrong!
🛡️

Prevention

To avoid uncaught exceptions, always use try-catch blocks around code that might throw errors, especially in asynchronous functions. Use promises with catch handlers or async/await with try-catch. Additionally, use linting tools like ESLint to detect missing error handling. Handling errors properly prevents your app from crashing unexpectedly.

⚠️

Related Errors

Similar errors include unhandledRejection, which happens when a Promise is rejected but not caught. You can handle it with process.on('unhandledRejection'). Both uncaught exceptions and unhandled rejections can crash your app if not handled.

javascript
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  // Recommended: shutdown or restart app
});

Key Takeaways

Always handle errors with try-catch or promise catch to prevent uncaught exceptions.
Use process.on('uncaughtException') to catch errors not handled elsewhere and clean up.
Exit the process after handling uncaught exceptions to avoid unstable state.
Use process.on('unhandledRejection') to catch unhandled promise rejections.
Lint your code to detect missing error handling early.