Node.jsJavaScriptError Fix2026 Updated

UnhandledPromiseRejectionWarning— Fixed [Complete Guide 2026]

January 20266 min readNode.js · All OS

⚡ Universal Fix — Add try/catch to Every async Function

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?

Terminal Warning / Error
(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.

PatternResult
await riskyFn() without try/catchUnhandled rejection if riskyFn() throws
somePromise() without .catch()Unhandled rejection if promise rejects
async function that throwsCaller must catch or it propagates
Promise.all([...]) without .catch()Any single rejection causes unhandled rejection
1

Add try/catch to Every async Function

The correct fix — handle errors where they occur
5 min
routes/users.js
// ❌ 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)
  }
})
2

Add .catch() to Promise Chains

For non-async/await code or fire-and-forget tasks
2 min
server.js
// ❌ 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
})
3

Add Global unhandledRejection Handler

Safety net — catch any missed rejections
2 min

Add 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.

server.js — line 1
// 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.

4

Fix Express Async Route Handlers

Express does not catch async errors automatically
3 min

Express 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).

server.js
// 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)
// })
5

asyncHandler Utility — Clean Up Repetitive try/catch

DRY pattern for Express routes
3 min

If every route handler repeats the same try/catch boilerplate, extract it into a utility wrapper.

utils/asyncHandler.js
// 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 = asyncHandler
routes/users.js
const 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.

6

Find Which Promise Is Rejecting

Use --trace-warnings to get full stack trace
2 min
terminal
# 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.js

The 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 versionUnhandled rejection behaviour
Node.js < 15Prints 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

Frequently Asked Questions

What causes UnhandledPromiseRejectionWarning?+
A promise was rejected but no .catch() handler or try/catch block was there to handle it. In Node.js 15+, this crashes the process. The warning includes the rejection reason — that tells you exactly what failed.
How do I fix UnhandledPromiseRejectionWarning?+
Add try/catch to every async function that might throw: try { await riskyOperation() } catch (err) { console.error(err) }. Or add .catch() to promise chains: fetchData().catch(err => console.error(err)).
UnhandledPromiseRejectionWarning crashes my server in production — why?+
Node.js 15 and above changed the default behaviour from warning to crash. An unhandled rejection now terminates the process. Add try/catch to your async code and use process.on('unhandledRejection') as a safety net.
How do I find which promise is rejecting?+
Node.js prints the rejection reason in the warning. Run with --trace-warnings: node --trace-warnings server.js. This shows the full stack trace including the exact line that created the unhandled promise.
Is it safe to suppress UnhandledPromiseRejectionWarning?+
No. The warning means an error occurred that you are not handling. Suppressing it hides bugs. Fix the root cause by adding proper error handling to the async code that is failing.
How do I handle errors in Express async routes?+
Wrap route logic in try/catch and call next(err) on error: app.get('/route', async (req, res, next) => { try { const data = await fetch(); res.json(data) } catch (err) { next(err) } }). Or use an asyncHandler wrapper utility.

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