Process Event: 'uncaughtException'
You'll learn how to catch errors that would otherwise crash your Node.js application, giving you a chance to log them gracefully.
What Are Uncaught Exceptions?
When an error is thrown in your Node.js code and nothing catches it (no try-catch, no Promise rejection handler), it becomes an uncaught exception. By default, Node.js will print the error and immediately terminate your process. The 'uncaughtException' event gives you one last chance to handle this situation before the crash.
Think of it like a safety net under a trapeze artist—it's your last line of defense when everything else has failed.
Listening for Uncaught Exceptions
You can attach a listener to the process object to intercept these fatal errors:
process.on('uncaughtException', (error) => {
console.error('CRITICAL ERROR:', error.message);
console.error(error.stack);
// Perform cleanup, log to file, alert monitoring service, etc.
process.exit(1); // Still exit with error code
});
// This error won't be caught anywhere
throw new Error('Something went terribly wrong!');
Important Warnings
This event is not a substitute for proper error handling. Your application is in an unknown state when this fires—data might be corrupted, connections might be broken. The Node.js documentation strongly recommends you always exit after logging the error, not try to continue running.
Use this event to:
- Log detailed error information
- Send alerts to monitoring systems
- Attempt graceful cleanup
- Then exit the process
Key Takeaway: The 'uncaughtException' event is your last-resort safety mechanism for logging fatal errors before Node.js terminates, but you should still exit the process afterward since the application state is unreliable.