How to Handle Uncaught Exceptions in Node.js Safely
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.
setTimeout(() => { // This error is not caught anywhere throw new Error('Something went wrong!'); }, 1000);
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.
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);
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.
process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection at:', promise, 'reason:', reason); // Recommended: shutdown or restart app });