UnhandledPromiseRejectionWarning
A promise was rejected but no catch handler was attached.
Usually happens because:
- ☑ Missing catch Chains
- ☑ Uncaught async functions
🔍 Quick Checklist:
What is UnhandledPromiseRejectionWarning?
The UnhandledPromiseRejectionWarning occurs in Node.js when an asynchronous Promise is rejected (fails), but no catch handler (.catch() or try-catch block) is registered to capture the exception. Since Node.js v15, this warning is treated as a fatal crash error that terminates the process automatically.
Common Causes
- Missing catch Chains: Leaving out .catch() blocks on async database queries or third-party fetches.
- Uncaught async functions: Throwing errors inside async functions without wrapper try-catch statements.
| Cause | Frequency |
|---|---|
| Missing catch Chains | ⭐⭐⭐⭐⭐ |
| Uncaught async functions | ⭐⭐⭐⭐ |
Common Mistakes
- Assuming Node.js ignores unhandled rejections (since Node 15, unhandled promise rejections terminate/crash the application process automatically).
How to Fix
Framework-Specific Examples
Utilizing express-async-errors to forward rejected promises automatically to Express error handlers.
require('express-async-errors');
app.get('/user', async (req, res) => {
const user = await db.fetchUser(); // Rejected promises are caught automatically
res.json(user);
});Server Configuration Examples
Logging and handling global process level rejections.
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Promise Rejection:', reason);
process.exit(1);
});Best Practices
- Use static analysis linters (like ESLint rules for floating promises).
- Implement global process error monitors.
Frequently Asked Questions (FAQ)
Q: Why does my Node.js application crash on unhandled rejections?
Since Node.js version 15, the default behavior for unhandled promise rejections has been upgraded from printing a warning to terminating the process immediately with a non-zero exit code.
Q: How do I catch all unhandled rejections globally?
Add a process event listener: `process.on('unhandledRejection', (reason, promise) => { ... });` to log the failure and close connection resources.
Q: Does async/await require try-catch?
Yes. If an await statement fails and is not wrapped in a try-catch block, it will result in an unhandled promise rejection.
Q: Can I ignore these warnings?
No. In modern Node.js, ignoring rejections leads to process crashes, exposing applications to denial of service.