Express error-handling middleware must have four parameters: err, req, res, and next. This signature tells Express to treat it as an error handler.
next(err) inside a middleware, what will Express do next?Calling next(err) tells Express to skip all normal middleware and jump to the next error-handling middleware (with four parameters).
function errorHandler(req, res, next) {
res.status(500).send('Something broke!');
}Express identifies error-handling middleware by the presence of four parameters: err, req, res, next. This function only has three, so Express treats it as normal middleware and will not call it on errors.
function errorHandler(err, req, res, next) {
if (err.status) {
res.status(err.status).send(err.message);
} else {
res.status(500).send('Internal Server Error');
}
}The middleware checks if err.status exists. If yes, it uses that status code; otherwise, it defaults to 500.
Express checks the number of parameters in middleware functions. Functions with four parameters are treated as error handlers. This is how Express knows to call them when an error occurs.