Complete the code to define an error-handling middleware 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 an error handler.
Complete the code to send a JSON error response with status code 400.
app.use(function(err, req, res, next) {
res.status([1]).json({ error: err.message });
});Status code 400 means a bad request. Here, we send the error message as JSON with status 400.
Fix the error in the middleware to correctly pass the error to the next handler.
app.use(function(err, req, res, next) {
if (!err) {
[1]();
} else {
res.status(500).send(err.message);
}
});res() which is not a function.err() which is not a function.Calling next() without arguments passes control to the next middleware. This is needed when there is no error.
Fill both blanks to create a middleware that logs the error message and then passes the error along.
app.use(function(err, req, res, next) {
console.[1](err.message);
[2](err);
});console.error instead of console.log (both work but only one is correct here).next() without the error argument.Use console.log to print the error message. Then call next(err) to pass the error to the next middleware.
Fill all three blanks to create a centralized error handler that sets status, logs error, and sends JSON response.
app.use(function(err, req, res, next) {
res.status([1]);
console.[2](err.stack);
res.json({ error: [3] });
});console.log instead of console.error.The status code 500 means server error. Use console.error to log the stack trace. Send the error message in JSON response.