Beginner LevelNode JS
How do you handle uncaughtException and unhandledRejection events in Node.js?
❓ Interview Prompt: Explain global error handling, process.on('uncaughtException'), process.on('unhandledRejection'), logging, and process exit.
When synchronous exceptions or asynchronous Promise rejections go unhandled, Node.js emits process-level safety events:
•
'process.on('unhandledRejection')': Emitted when a Promise is rejected without a '.catch()' block.
•
'process.on('uncaughtException')': Emitted when an uncaught JavaScript exception bubbles up to the event loop. Crucial: Log the error and exit 'process.exit(1)' because the process state is corrupted!
Code Implementation Example
javascript
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Promise Rejection:', reason);
});
process.on('uncaughtException', (err) => {
console.error('Fatal Uncaught Exception! Exiting process...', err);
process.exit(1); // Always exit to let orchestrators restart process!
});💡Registering process-level uncaughtException and unhandledRejection handlers.
🎯 Interview Key Takeaway
Always log uncaught exceptions and exit the process immediately so process managers (PM2/Kubernetes) can restart a clean instance.
#uncaughtException#unhandledRejection#Error Handling#Beginner
Back to all Node JS Questions→