Complete the code to add a basic error handler middleware in Express.
app.use(function(err, req, [1], next) { res.status(500).send('Something broke!'); });
The error handler middleware in Express must have four parameters: err, req, res, and next. Here, res is the response object used to send the error message.
Complete the code to catch errors in an async route handler using Express.
app.get('/data', async (req, res, [1]) => { try { const data = await fetchData(); res.json(data); } catch (err) { next(err); } });
The next function is used to pass errors to Express's error handler. It must be included as the third parameter in the route handler.
Fix the error in the middleware to properly handle errors in Express.
function errorHandler(err, req, res, [1]) { res.status(500).json({ message: err.message }); }
The fourth parameter in an Express error handler middleware must be next to properly handle the error flow.
Fill both blanks to create a middleware that logs errors and passes them on.
function logErrors(err, [1], [2], next) { console.error(err.stack); next(err); }
The error logging middleware receives err, req, res, and next as parameters. Here, req and res represent the request and response objects.
Fill all three blanks to create a custom error class and use it in Express.
class [1] extends Error { constructor(message) { super(message); this.status = [2]; } } app.use((err, req, res, next) => { if (err instanceof [3]) { res.status(err.status).send(err.message); } else { next(err); } });
This code defines a custom error class named CustomError that extends the built-in Error. It sets a status property, here 404. The middleware checks if the error is an instance of CustomError to handle it properly.