0
0
Expressframework~10 mins

Why error handling is critical in Express - Test Your Understanding

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

Complete the code to add a basic error handler middleware in Express.

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

Complete the code to catch errors in an async route handler using Express.

Express
app.get('/data', async (req, res, [1]) => {
  try {
    const data = await fetchData();
    res.json(data);
  } catch (err) {
    next(err);
  }
});
Drag options to blanks, or click blank then click option'
Aresponse
Berror
Cres
Dnext
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to include 'next' as a parameter.
Trying to handle errors without calling 'next(err)'.
3fill in blank
hard

Fix the error in the middleware to properly handle errors in Express.

Express
function errorHandler(err, req, res, [1]) {
  res.status(500).json({ message: err.message });
}
Drag options to blanks, or click blank then click option'
Anext
Berror
Cresponse
Dres
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'res' or 'response' instead of 'next' as the fourth parameter.
Omitting the fourth parameter entirely.
4fill in blank
hard

Fill both blanks to create a middleware that logs errors and passes them on.

Express
function logErrors(err, [1], [2], next) {
  console.error(err.stack);
  next(err);
}
Drag options to blanks, or click blank then click option'
Areq
Bres
Crequest
Dresponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'request' and 'response' instead of 'req' and 'res'.
Swapping the order of parameters.
5fill in blank
hard

Fill all three blanks to create a custom error class and use it in Express.

Express
class [1] extends Error {
  constructor(message) {
    super(message);
    this.status = [2];
  }
}

app.use((err, req, res, next) => {
  if (err instanceof [3]) {
    res.status(err.status).send(err.message);
  } else {
    next(err);
  }
});
Drag options to blanks, or click blank then click option'
AHttpError
B404
DCustomError
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the class and instance check.
Setting status as a string instead of a number.