0
0
Node.jsframework~10 mins

Error-handling middleware 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 define an error-handling middleware function in Express.

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 only three parameters instead of four.
Naming the fourth parameter incorrectly.
2fill in blank
medium

Complete the code to send a JSON error response with status 400.

Node.js
app.use(function(err, req, res, next) {
  res.status([1]).json({ error: err.message });
});
Drag options to blanks, or click blank then click option'
A404
B200
C400
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using 200 which means success.
Using 500 which means server error instead of client error.
3fill in blank
hard

Fix the error in the middleware signature to correctly handle errors.

Node.js
app.use(function([1], req, res, next) {
  res.status(500).send('Error occurred');
});
Drag options to blanks, or click blank then click option'
Aerror
Berr
Cnext
Drequest
Attempts:
3 left
💡 Hint
Common Mistakes
Placing the error parameter last instead of first.
Using wrong parameter names.
4fill in blank
hard

Fill both blanks to correctly pass the error to the next middleware.

Node.js
app.use(function(err, req, res, [1]) {
  if (err) {
    [2](err);
  } else {
    next();
  }
});
Drag options to blanks, or click blank then click option'
Anext
Bres
Csend
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Calling res or send instead of next.
Using wrong parameter names.
5fill in blank
hard

Fill all three blanks to create a middleware that logs the error and sends a 500 response.

Node.js
app.use(function([1], [2], [3], next) {
  console.error([1].message);
  res.status(500).send('Internal Server Error');
});
Drag options to blanks, or click blank then click option'
Aerr
Breq
Cres
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of parameters.
Forgetting to log the error message.