Unhandled promise rejections occur when no ‘.catch()‘ is attached to a promise, and the promise gets rejected. In Node.js, you can handle unhandled promise rejections by two main mechanisms: attaching a global event handler to the ‘process‘ object for the ‘unhandledRejection‘ event or using ‘async-await‘ combined with a ‘try-catch‘ statement.
Let’s discuss both methods in detail with examples.
1. Handling unhandled promise rejections using ‘process.on(’unhandledRejection’)‘:
To handle all unhandled promise rejections globally in your application, you can attach an event handler to the ‘unhandledRejection‘ event on the ‘process‘ object. The event handler will receive the rejection reason and the promise that was rejected.
Example:
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'Reason:', reason);
// Handle the rejection, log the error, or perform any other custom action
});
2. Handling unhandled promise rejections using ‘async-await‘ with ‘try-catch‘:
By converting your promise-based operations into ‘async-await‘, you can handle unhandled promise rejections in a more familiar way with a ‘try-catch‘ statement. Just remember that you need to make your function ‘async‘ to use the ‘await‘ keyword inside it.
Example:
// Assuming that `fetchData` is a function that returns a promise
const fetchData = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Request timed out'));
}, 5000);
});
};
const fetchDataWrapper = async () => {
try {
const data = await fetchData();
console.log('Data fetched:', data);
} catch (error) {
console.error('Fetch data failed:', error);
// Handle the error, log it, or perform any other custom action
}
};
fetchDataWrapper();
With ‘async-await‘, you can pass the error up the call chain until it reaches a ‘try-catch‘ block or, in the case where there is no ‘try-catch‘ block, the ‘unhandledRejection‘ handler will still step in when no other rejection handler was attached.
These are the two main mechanisms to handle unhandled promise rejections in Node.js applications. Choose the one that better suits your needs or use them in combination to make sure errors are properly caught and handled.