How to handle errors globally — Intermediate
Use a centralized errorHandler middleware to format errors and set status codes.
Learn: Express recognizes error-handling middleware by its four arguments `(err, req, res, next)`. Log the error, map known status codes, and avoid leaking stack traces in production.
Supplementary examples
Central error handler
function errorHandler(err, req, res, next) {
const status = err.status || err.statusCode || 500;
req.log?.error(err);
res.status(status).json({
error: err.message || "Internal Server Error",
});
}
app.use(errorHandler); // after notFoundCourse example
const checkForAbbreviationLength = (req, res, next) => {
const abbreviation = req.params.abbreviation;
if (abbreviation.length !== 2) {
next("State abbreviation is invalid.");
} else {
next();
}
};
Additional references & examples
- Express.js guide
Routing, middleware order, and request/response lifecycle.
- Express error handling
How to define and propagate errors to a central handler.