Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a basic Express error handler middleware.
Node.js
app.use(function(err, req, res, [1]) { res.status(500).send('Something broke!'); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' instead of 'next' as the last parameter.
Missing the fourth parameter entirely.
✗ Incorrect
The error handler middleware in Express requires four parameters: err, req, res, and next. The 'next' parameter is used to pass control to the next middleware.
2fill in blank
mediumComplete the code to forward an error to the centralized error handler.
Node.js
app.get('/', (req, res, [1]) => { const err = new Error('Oops!'); [1](err); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' or 'handle' instead of 'next'.
Not calling any function to forward the error.
✗ Incorrect
In Express, calling 'next' with an error object forwards the error to the centralized error handler middleware.
3fill in blank
hardFix the error in the centralized error handler to send JSON response.
Node.js
app.use((err, req, res, next) => {
res.status(500).[1]({ error: err.message });
}); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'sendText' or 'render' which are not valid methods for JSON response.
Forgetting to send the error message in JSON format.
✗ Incorrect
To send a JSON response in Express, use the 'json' method on the response object.
4fill in blank
hardFill both blanks to create a middleware that catches 404 errors and forwards them to the error handler.
Node.js
app.use((req, res, [1]) => { const err = new Error('Not Found'); err.status = 404; [2](err); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' or 'send' instead of 'next'.
Not forwarding the error to the next middleware.
✗ Incorrect
The middleware uses 'next' to pass control and forward the error to the centralized error handler.
5fill in blank
hardFill all three blanks to create a centralized error handler that logs the error, sets status, and sends JSON response.
Node.js
app.use((err, req, res, [1]) => { console.error(err.[2]); res.status(err.status || 500).[3]({ message: err.message }); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Logging 'message' instead of 'stack'.
Using 'send' instead of 'json' for response.
Missing the 'next' parameter.
✗ Incorrect
The error handler uses 'next' as the last parameter, logs the error stack, and sends a JSON response with the error message.