What is unhandledRejection in Node.js: Explanation and Example
unhandledRejection in Node.js is an event that fires when a Promise is rejected but no error handler is attached to catch it. It helps developers detect and handle errors that would otherwise be missed, preventing unexpected crashes or silent failures.How It Works
Imagine you promise to do a task, but something goes wrong and you never tell anyone about the problem. In Node.js, Promises are like these promises. When a Promise fails (rejects) and no one listens for that failure, Node.js triggers the unhandledRejection event.
This event acts like a safety net, catching errors that slip through without a handler. It lets you know that something went wrong but was ignored, so you can fix it before it causes bigger issues.
Without this event, your program might continue running with hidden errors, which can lead to bugs or crashes later on. Handling unhandledRejection is like having a smoke alarm for your asynchronous code.
Example
This example shows a Promise that rejects without a catch handler. Node.js will emit the unhandledRejection event, which we listen for to log the error.
process.on('unhandledRejection', (reason, promise) => { console.log('Caught unhandled rejection:', reason.message); }); // Create a Promise that rejects but has no catch new Promise((resolve, reject) => { reject(new Error('Something went wrong')); });
When to Use
You should use the unhandledRejection event to catch errors from Promises that you might have missed handling. This is especially useful in large applications where many asynchronous operations happen.
It helps you find bugs early by logging or cleaning up resources before the program crashes. For example, in a web server, you can log these errors and send alerts to fix issues quickly.
However, it is best practice to handle Promise rejections locally with catch or try/catch in async functions. The unhandledRejection event is a last-resort safety net, not a replacement for proper error handling.
Key Points
unhandledRejectionfires when a Promise rejects without a handler.- It helps detect silent errors in asynchronous code.
- Use it to log or clean up before your app crashes.
- Always prefer handling rejections locally with
catch. - It acts like a safety net for missed Promise errors.
Key Takeaways
unhandledRejection event catches Promise errors without handlers to prevent silent failures.catch or try/catch in async functions.unhandledRejection to log errors and clean up resources before your app crashes.unhandledRejection as a safety net, not a substitute for proper error handling.