UnhandledPromiseRejectionWarning— Fixed [Complete Guide 2026]
⚡ Universal Fix — Add try/catch to Every async Function
// ❌ WRONG — rejection not handled
async function loadUser(id) {
const user = await User.findById(id) // if this throws → UnhandledRejection
return user
}
// ✅ CORRECT — catch and handle the rejection
async function loadUser(id) {
try {
const user = await User.findById(id)
return user
} catch (err) {
console.error('loadUser failed:', err.message)
return null // or throw, depending on context
}
}What Causes UnhandledPromiseRejectionWarning?
(node:12345) UnhandledPromiseRejectionWarning: MongoServerError: Authentication failed
(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().
(Use `node --pending-deprecation` to see where the warning was created)
(node:12345) [DEP0018] DeprecationWarning: Unhandled promise rejections are
deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.This warning fires when a promise rejects — throws an error — and no .catch() handler or try/catch block is present to handle it. The warning message always includes the rejection reason — read it carefully, it tells you exactly what failed.
| Pattern | Result |
|---|---|
| await riskyFn() without try/catch | Unhandled rejection if riskyFn() throws |
| somePromise() without .catch() | Unhandled rejection if promise rejects |
| async function that throws | Caller must catch or it propagates |
| Promise.all([...]) without .catch() | Any single rejection causes unhandled rejection |
Add try/catch to Every async Function
The correct fix — handle errors where they occur// ❌ WRONG — no error handling
app.get('/users/:id', async (req, res) => {
const user = await User.findById(req.params.id) // throws → UnhandledRejection
res.json(user)
})
// ✅ CORRECT — every await wrapped in try/catch
app.get('/users/:id', async (req, res, next) => {
try {
const user = await User.findById(req.params.id)
if (!user) return res.status(404).json({ error: 'User not found' })
res.json(user)
} catch (err) {
next(err) // passes to Express error middleware
}
})
// ✅ Multiple awaits — one try/catch covers all of them
app.post('/orders', async (req, res, next) => {
try {
const user = await User.findById(req.body.userId)
const product = await Product.findById(req.body.productId)
const order = await Order.create({ user, product })
res.status(201).json(order)
} catch (err) {
next(err)
}
})Add .catch() to Promise Chains
For non-async/await code or fire-and-forget tasks// ❌ WRONG — promise chain with no .catch()
mongoose.connect(process.env.MONGODB_URI)
.then(() => console.log('DB connected'))
// if connect() rejects → UnhandledRejection
// ✅ CORRECT — always chain .catch()
mongoose.connect(process.env.MONGODB_URI)
.then(() => console.log('DB connected'))
.catch(err => {
console.error('DB connection failed:', err.message)
process.exit(1)
})
// ✅ Fire-and-forget tasks — must still handle rejection
function sendEmailAsync(to, subject) {
mailer.sendMail({ to, subject })
.then(() => console.log('Email sent'))
.catch(err => console.error('Email failed:', err.message))
// Do NOT just call: mailer.sendMail({ to, subject }) with no handler
}
// ✅ Promise.all — catch covers all
const [users, products] = await Promise.all([
User.find(),
Product.find(),
]).catch(err => {
console.error('Batch query failed:', err)
throw err
})Add Global unhandledRejection Handler
Safety net — catch any missed rejectionsAdd this to the very top of your entry file as a last-resort safety net. It catches any rejection that slipped past your try/catch blocks.
// Safety net — add at very top of entry file
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise)
console.error('Reason:', reason)
// Log to your error tracker (Sentry etc.) here
// Do NOT silently suppress — the underlying error is real
})The global handler is a safety net, not a solution. It does not fix the underlying unhandled rejection — it just prevents the crash. Track down and fix the missing try/catch.
Fix Express Async Route Handlers
Express does not catch async errors automaticallyExpress 4 does not automatically catch errors thrown in async route handlers. You must either use try/catch with next(err) or use Express 5 (which handles async errors automatically).
// Express 4 — manual try/catch required
app.get('/data', async (req, res, next) => {
try {
const data = await fetchData()
res.json(data)
} catch (err) {
next(err) // passes to error middleware below
}
})
// Error middleware — MUST be last, MUST have 4 params
app.use((err, req, res, next) => {
console.error(err)
res.status(err.status || 500).json({ error: err.message })
})
// Express 5 — async errors caught automatically (no try/catch needed)
// npm install express@5
// app.get('/data', async (req, res) => {
// const data = await fetchData() // throws → caught by Express 5
// res.json(data)
// })asyncHandler Utility — Clean Up Repetitive try/catch
DRY pattern for Express routesIf every route handler repeats the same try/catch boilerplate, extract it into a utility wrapper.
// Wraps an async function and automatically calls next(err) on rejection
const asyncHandler = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next)
module.exports = asyncHandlerconst asyncHandler = require('../utils/asyncHandler')
// No try/catch needed — asyncHandler handles rejections
router.get('/:id', asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id)
if (!user) return res.status(404).json({ error: 'Not found' })
res.json(user)
}))
router.post('/', asyncHandler(async (req, res) => {
const user = await User.create(req.body)
res.status(201).json(user)
}))
router.delete('/:id', asyncHandler(async (req, res) => {
await User.findByIdAndDelete(req.params.id)
res.json({ deleted: true })
}))The 'express-async-errors' package patches Express globally to catch async errors: just require('express-async-errors') at the top of your app — no wrapper needed.
Find Which Promise Is Rejecting
Use --trace-warnings to get full stack trace# Show full stack trace for all warnings
node --trace-warnings server.js
# Output will include:
# (node:12345) UnhandledPromiseRejectionWarning: Error: ...
# at processTicksAndRejections (node:internal/process/task_queues:95:5)
# at async User.findById (/app/routes/users.js:12:20) ← LINE 12!
# Also useful: enable async stack traces
node --async-stack-traces server.js
# With NODE_OPTIONS env var (no code change needed)
NODE_OPTIONS='--trace-warnings' node server.jsThe stack trace shows the exact file and line number where the rejected promise was created. Go to that line and add try/catch.
Node.js 15+ — Unhandled Rejections Crash the Process
Before Node.js 15, unhandled promise rejections printed a warning but the process continued running. From Node.js 15 onwards, they terminate the process with exit code 1.
| Node version | Unhandled rejection behaviour |
|---|---|
| Node.js < 15 | Prints DeprecationWarning — process continues |
| Node.js 15+ | Terminates process with non-zero exit code |
If your app suddenly started crashing after a Node upgrade, this is why. The same unhandled rejections that were warnings before are now crashes.
How to Prevent Unhandled Rejections
- Add try/catch to every async function — no exceptions
- Always chain .catch() on promise chains that are not awaited
- Add process.on('unhandledRejection') as a global safety net
- Use asyncHandler wrapper or express-async-errors package for Express routes
- Add error middleware (4 params) as last middleware in Express
- Run node --trace-warnings to see stack traces for remaining warnings
- Consider upgrading to Express 5 which catches async route errors automatically
Frequently Asked Questions
What causes UnhandledPromiseRejectionWarning?+−
How do I fix UnhandledPromiseRejectionWarning?+−
UnhandledPromiseRejectionWarning crashes my server in production — why?+−
How do I find which promise is rejecting?+−
Is it safe to suppress UnhandledPromiseRejectionWarning?+−
How do I handle errors in Express async routes?+−
Need Expert Help?
We Build Production-Grade Node.js Apps
Softplix builds full-stack applications with robust error handling. Dealing with promise handling issues in production? We can help.
Talk to an Engineer