Sequence NODE_244
Medium

Implement Centralized Error Handling Middleware

Express.js
Node.js
Technical Specification

Add an error-handling middleware that catches thrown errors and returns a standardized JSON error response.

Input/Output Samples
Input:Route throws error
Output:{ "error": "Something failed" }
Optimal Logic Path
function errorHandler(err, req, res, next) {
  console.error(err);
  const status = err.status || 500;
  res.status(status).json({
    error: err.message || "Internal Server Error",
  });
}

app.use(errorHandler);
Architectural Deep-Dive
Any error passed to next(err) or thrown in async handlers can be handled in one central place.