How to Handle Unhandled Rejection in Node.js: Simple Fixes
process.on('unhandledRejection') event to catch these errors globally and add .catch() handlers to promises to handle errors properly.Why This Happens
Unhandled promise rejections occur when a promise throws an error but no .catch() handler is attached to handle it. Node.js then warns you because the error might crash your app or cause unexpected behavior.
const promise = new Promise((resolve, reject) => { reject(new Error('Oops!')); }); // No .catch() attached to handle rejection
The Fix
Always attach a .catch() handler to promises to handle errors. Additionally, listen to the unhandledRejection event on process to catch any missed errors and log or handle them gracefully.
const promise = new Promise((resolve, reject) => { reject(new Error('Oops!')); }); promise.catch(error => { console.error('Caught error:', error.message); }); process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection at:', promise, 'reason:', reason); // You can log the error or exit process if needed });
Prevention
To avoid unhandled rejections, always add .catch() to promises or use try/catch inside async functions. Use linting tools like ESLint with rules that warn about missing promise error handling. Also, handle the unhandledRejection event to catch any unexpected errors and keep your app stable.
Related Errors
Similar errors include uncaughtException, which happens when an error is thrown but not caught anywhere in synchronous code. Handle it with process.on('uncaughtException'). Also, beware of memory leaks caused by unhandled rejections piling up without proper cleanup.