0
0
Expressframework~10 mins

Centralized error handler 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]) {
  res.status(500).send('Something broke!');
});
Drag options to blanks, or click blank then click option'
Arequest
Bres
Cerror
Dnext
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 code 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
B404
C200
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using status 200 which means success.
Using status 404 which means not found.
3fill in blank
hard

Fix the error in the middleware to correctly pass the error to the next handler.

Express
app.use(function(err, req, res, next) {
  if (!err) {
    [1]();
  } else {
    res.status(500).send(err.message);
  }
});
Drag options to blanks, or click blank then click option'
Areq
Bres
Cnext
Derr
Attempts:
3 left
💡 Hint
Common Mistakes
Calling res() which is not a function.
Calling err() which is not a function.
4fill in blank
hard

Fill both blanks to create a middleware that logs the error message and then passes the error along.

Express
app.use(function(err, req, res, next) {
  console.[1](err.message);
  [2](err);
});
Drag options to blanks, or click blank then click option'
Alog
Bnext
Cerror
Dwarn
Attempts:
3 left
💡 Hint
Common Mistakes
Using console.error instead of console.log (both work but only one is correct here).
Calling next() without the error argument.
5fill in blank
hard

Fill all three blanks to create a centralized error handler that sets status, logs error, and sends JSON response.

Express
app.use(function(err, req, res, next) {
  res.status([1]);
  console.[2](err.stack);
  res.json({ error: [3] });
});
Drag options to blanks, or click blank then click option'
A500
Berror
Cerr.message
Dwarn
Attempts:
3 left
💡 Hint
Common Mistakes
Using status 200 instead of 500.
Logging with console.log instead of console.error.
Sending the whole error object instead of just the message.