Complete the code to define an error-handling middleware function in Express.
app.use(function(err, req, res, [1]) { res.status(500).send('Something broke!'); });
The error-handling middleware in Express must have four parameters: err, req, res, and next. The next parameter is required to identify it as error-handling middleware.
Complete the code to send a JSON error response with status 400.
app.use(function(err, req, res, next) {
res.status([1]).json({ error: err.message });
});Status code 400 means a bad request error. Here, we want to send that status code when an error occurs.
Fix the error in the middleware signature to correctly handle errors.
app.use(function([1], req, res, next) { res.status(500).send('Error occurred'); });
The error-handling middleware must have the error parameter as the first argument. The correct order is err, req, res, next. Here, the error parameter is misplaced and must be fixed.
Fill both blanks to correctly pass the error to the next middleware.
app.use(function(err, req, res, [1]) { if (err) { [2](err); } else { next(); } });
res or send instead of next.The fourth parameter is next, which is a function to pass control to the next middleware. To forward the error, we call next(err).
Fill all three blanks to create a middleware that logs the error and sends a 500 response.
app.use(function([1], [2], [3], next) { console.error([1].message); res.status(500).send('Internal Server Error'); });
The error-handling middleware parameters are err, req, res, and next. We log the error message from err and send a 500 response using res.