Complete the code to create an Express error handler middleware.
app.use(function(err, req, res, [1]) { res.status(500).send('Something broke!'); });
next parameter causes Express not to recognize the middleware as an error handler.The error handler middleware in Express must have four parameters: err, req, res, and next. The next parameter is required even if not used.
Complete the code to throw a synchronous error inside a route handler.
app.get('/', (req, res) => { throw new [1]('Oops!'); });
To throw an error in JavaScript, use the Error constructor. This creates a proper error object that Express can catch.
Fix the error in the middleware to correctly pass the error to the next handler.
app.use((req, res, next) => {
const err = new Error('Not found');
[1](err);
});throw inside async middleware causes unhandled exceptions.res.send does not forward the error.To pass an error to the next middleware in Express, call next(err). Throwing the error or returning it does not work here.
Fill both blanks to create an error handler that logs the error and sends a 500 status.
app.use(function(err, req, res, [1]) { console.[2](err.message); res.status(500).send('Server error'); });
console.log instead of console.error for errors.next parameter.The error handler middleware must have next as the fourth parameter. To log errors, use console.error for clear error messages.
Fill all three blanks to create a route that catches synchronous errors and passes them to the error handler.
app.get('/data', (req, res, [1]) => { try { throw new [2]('Failed to load data'); } catch (err) { [3](err); } });
next(err) inside the catch block.res instead of next to forward errors.The third parameter in route handlers is next. Use Error to create an error object. Call next(err) inside catch to forward the error.