Q13: How do you write an Error-Handling Middleware in Express?

Difficulty:MediumTopic:Error Handling

Express error-handling middleware must explicitly declare four parameters: (err, req, res, next). Omitting any parameter (even next) causes Express to treat it as standard middleware.

Centralized Error Handler Implementation
// Must be registered LAST, after all app.use() and route calls
app.use((err, req, res, next) => {
  console.error(err.stack);
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    status: 'error',
    message: err.message || 'Internal Server Error'
  });
});
💡 Global error handling middleware intercepts uncaught operational errors forwarded via next(err).
Key Takeaways
  • Must accept exactly 4 arguments (err, req, res, next).
  • Must be mounted at the bottom of the middleware chain after all route handlers.