CPCODELAB
Express

Error-Handling Middleware

9 min read

Error-Handling Middleware

Error-handling middleware has four parameters: (err, req, res, next). Express recognises it as an error handler by that exact arity. It is always registered last, after all routes and regular middleware.

js
// Route that throws
app.get("/fail", (req, res, next) => {
  const err = new Error("Something went wrong");
  next(err); // pass the error downstream
});

// Error handler — must be the last app.use call
app.use((err, req, res, next) => {
  console.error(err.stack);
  const status = err.status ?? 500;
  res.status(status).json({
    error: err.message || "Internal Server Error"
  });
});

In Express 5, route handlers that return a rejected Promise or throw synchronously are automatically forwarded to the error handler without needing an explicit try/catch or next(err) in every route.

Create a central errorHandler.ts module, export the four-argument function, and import it in app.ts. This keeps all error-handling logic in one maintainable place.

Ready to test yourself?
Practice Express— quiz & coding exercises