0
0
Node.jsframework~10 mins

Centralized error handling in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Anext
Berror
Cresponse
Drequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' instead of 'next' as the last parameter.
Missing the fourth parameter entirely.
2fill in blank
medium

Complete 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'
Anext
Berror
Chandle
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' or 'handle' instead of 'next'.
Not calling any function to forward the error.
3fill in blank
hard

Fix 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'
AsendFile
BsendText
Cjson
Drender
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.
4fill in blank
hard

Fill 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'
Anext
Berror
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' or 'send' instead of 'next'.
Not forwarding the error to the next middleware.
5fill in blank
hard

Fill 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'
Anext
Bstack
Cjson
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Logging 'message' instead of 'stack'.
Using 'send' instead of 'json' for response.
Missing the 'next' parameter.