debugjavascriptnodejsCriticalpending
Debug: Node.js unhandled promise rejections causing crashes
Viewed 0 times
unhandled rejectionpromisecrashno-floating-promisesasync error
Error Messages
Problem
Node.js process crashes with UnhandledPromiseRejection or silently swallows promise errors.
Solution
Find and fix unhandled rejections:
// 1. Global handler to catch and log
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
// In production: log to error tracking, then exit
process.exit(1);
});
// 2. Common patterns that cause unhandled rejections:
// Missing .catch()
async function fetchUser() { /* might throw */ }
fetchUser(); // No catch! Add: fetchUser().catch(console.error);
// Missing await in try/catch
async function handler() {
try {
doSyncThing();
fetchData(); // Not awaited! Error escapes try/catch
} catch (e) {
// Won't catch fetchData errors
}
}
// Fix: await fetchData();
// Promise.all without catch
Promise.all([fetchA(), fetchB()]); // Add .catch()
// Event emitter async handlers
emitter.on('data', async (data) => {
await process(data); // Rejection not caught!
});
// Fix: wrap in try/catch
emitter.on('data', async (data) => {
try {
await process(data);
} catch (e) {
console.error('Processing error:', e);
}
});- Node.js 15+: Unhandled rejections crash by default (--unhandled-rejections=throw)
- ESLint: Use
eslint-plugin-promisewithno-floating-promisesrule - TypeScript: Enable
@typescript-eslint/no-floating-promises
Why
Unhandled promise rejections represent bugs where errors are silently lost. Node.js now treats them as crashes by default.
Context
Node.js applications with async/promise-based code
Revisions (0)
No revisions yet.