Unhandled promise rejections happen when a promise fails but no code catches the error. Handling them helps keep your program stable and avoid crashes.
Unhandled rejection handling in Node.js
process.on('unhandledRejection', (reason, promise) => {
// handle the error here
});This listens for any promise rejection that was not caught.
The reason is the error or value that caused the rejection.
process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled rejection:', reason); });
process.on('unhandledRejection', (reason, promise) => { // Exit the process after logging console.error('Error:', reason); process.exit(1); });
This program listens for unhandled promise rejections and logs the error message. The promise rejects without a catch, so the handler runs.
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('Oops!')); });
Always try to handle promise errors with .catch() or try/catch in async functions.
Use unhandled rejection handling as a safety net, not a replacement for proper error handling.
In Node.js 15+, unhandled rejections may cause the process to exit by default, so handling them is important.
Unhandled rejection handling catches errors from promises that no one caught.
It helps keep your app stable and lets you log or clean up on errors.
Use process.on('unhandledRejection') to listen and respond to these errors.