How to Fix Unhandled Promise Rejection in Node.js
To fix
unhandled promise rejection in Node.js, always handle promise errors using try/catch with async/await or attach a .catch() handler to promises. This ensures errors are caught and prevents the program from crashing or showing warnings.Why This Happens
An unhandled promise rejection happens when a promise fails (rejects) but no code catches that failure. Node.js then warns you because the error might crash your app or cause unexpected behavior.
This usually occurs when you forget to add error handling to asynchronous code using promises.
javascript
const fs = require('fs').promises; async function readFile() { const data = await fs.readFile('nonexistent.txt', 'utf8'); console.log(data); } readFile();
Output
(node:12345) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open 'nonexistent.txt'
(node:12345) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
The Fix
To fix this, add error handling by wrapping your await calls in try/catch blocks or by adding a .catch() method to your promise. This catches errors and lets you handle them gracefully.
javascript
const fs = require('fs').promises; async function readFile() { try { const data = await fs.readFile('nonexistent.txt', 'utf8'); console.log(data); } catch (error) { console.error('Failed to read file:', error.message); } } readFile();
Output
Failed to read file: ENOENT: no such file or directory, open 'nonexistent.txt'
Prevention
Always handle promise rejections by:
- Using
try/catchwithasync/await. - Adding
.catch()to promises when not usingasync/await. - Listening to the
process.on('unhandledRejection')event to log or handle unexpected rejections globally. - Using linting tools like ESLint with rules that warn about unhandled promises.
javascript
process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection at:', promise, 'reason:', reason); // Application specific logging, cleanup or exit });
Related Errors
Other common errors related to promises include:
- Unhandled exceptions: Errors thrown synchronously without try/catch.
- Callback hell: Nested callbacks causing hard-to-read code, avoid by using promises.
- Memory leaks: Caused by forgotten promise chains or listeners.
Fix these by using proper error handling and modern async patterns.
Key Takeaways
Always handle promise errors with try/catch or .catch() to avoid unhandled rejections.
Use process.on('unhandledRejection') to catch unexpected promise errors globally.
Lint your code to detect missing promise error handling early.
Proper error handling prevents app crashes and improves reliability.