Node.js process crashes with an unhandled promise rejection instead of just warning
Quick answer
Since Node.js 15, an unhandled promise rejection terminates the process by default instead of only printing a warning. Add a top-level `process.on('unhandledRejection', ...)` as a safety net, but the real fix is making sure every async call path actually has a `.catch()` or a surrounding try/catch.
What causes this error
Older Node versions just logged a DeprecationWarning for unhandled rejections and kept running. Since Node 15, the default behavior (--unhandled-rejections=throw) is to raise the rejection as an uncaught exception, which crashes the process — treating it with the same severity as a synchronous uncaught throw.
The Fix
// Add a safety-net listener so you at least see what's failing
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection:', reason);
// Log it, alert on it — but the real fix is below
});
// The actual fix: every async call site needs error handling
async function loadUser(id) {
try {
return await db.user.findUnique({ where: { id } });
} catch (err) {
logger.error(err);
throw err; // rethrow deliberately, don't swallow silently
}
}Common causes / variations
- A `.then()` chain missing a trailing `.catch()`
- Firing off an async function without awaiting it or attaching a handler (`doThing()` instead of `await doThing()` or `doThing().catch(...)`)
- An event handler or callback that's `async` but whose caller has no way to see the rejection
Related errors
See also: UnhandledPromiseRejectionWarning in Express route handlers.
Was this fix helpful?
Comments
Loading comments...