0
0
Expressframework~10 mins

Error-handling middleware in Express - 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 in Express.

Express
app.use(function(err, req, res, [1], next) {
  res.status(500).send('Something broke!');
});
Drag options to blanks, or click blank then click option'
Ares
Berror
Cnext
Drequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'res' or 'request' as the fourth parameter instead of 'next'.
Omitting the fourth parameter entirely.
2fill in blank
medium

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

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

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

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

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

Express
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
Using res or send instead of next.
Not calling next with the error.
5fill in blank
hard

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

Express
app.use(function([1], req, res, [2]) {
  console.error([3]);
  res.status(500).send('Server error');
});
Drag options to blanks, or click blank then click option'
Aerr
Bnext
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up parameter names.
Not logging the error correctly.