How to handle errors in Express applications

· Category: Node.js

Short answer

Define an error-handling middleware with four arguments (err, req, res, next) at the end of your middleware stack to catch and respond to errors centrally.

Steps

  1. Create a custom error class or use the built-in Error object.
  2. In route handlers, pass errors to next(err) to trigger error middleware.
  3. Define error middleware last: app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });.
  4. For async handlers, wrap them in a utility that catches rejected promises and calls next(err).
  5. Log errors before sending responses to aid debugging.

Tips

  • Use a library like express-async-handler to avoid repetitive try/catch blocks in async routes.
  • Never leak stack traces or internal details to clients in production; log them server-side instead.

Common issues

  • Error middleware must have exactly four parameters, or Express treats it as regular middleware.
  • Unhandled promise rejections in async routes can crash the server unless properly caught.