Error Handling Middleware in Node.js

From the Express.js cheat sheet · Error Handling · verified Jul 2026

Error Handling Middleware

Catch and handle errors gracefully in your Express application

javascript
// Async route handler wrapper
const asyncHandler = fn => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

// Route with async handling
app.get('/users/:id', asyncHandler(async (req, res) => {
  const user = await User.findById(req.params.id);
  res.json(user);
}));

// Global error handler (must be last)
app.use((err, req, res, next) => {
  console.error(err.stack);
  
  res.status(err.status || 500).json({
    message: err.message,
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
});
💡 Error middleware needs 4 parameters (err, req, res, next)
⚠️ Must be defined after all other middleware
✅ Use async wrapper to catch Promise rejections
🔒 Don't expose stack traces in production
Back to the full Express.js cheat sheet