0
0
Expressframework~10 mins

Synchronous error handling 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 create an Express error handler middleware.

Express
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
Omitting the next parameter causes Express not to recognize the middleware as an error handler.
2fill in blank
medium

Complete the code to throw a synchronous error inside a route handler.

Express
app.get('/', (req, res) => {
  throw new [1]('Oops!');
});
Drag options to blanks, or click blank then click option'
AException
BError
CString
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Throwing a string instead of an Error object prevents Express from handling the error properly.
3fill in blank
hard

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

Express
app.use((req, res, next) => {
  const err = new Error('Not found');
  [1](err);
});
Drag options to blanks, or click blank then click option'
Anext
Bthrow
Cres.send
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using throw inside async middleware causes unhandled exceptions.
Calling res.send does not forward the error.
4fill in blank
hard

Fill both blanks to create an error handler that logs the error and sends a 500 status.

Express
app.use(function(err, req, res, [1]) {
  console.[2](err.message);
  res.status(500).send('Server error');
});
Drag options to blanks, or click blank then click option'
Anext
Blog
Cerror
Dwarn
Attempts:
3 left
💡 Hint
Common Mistakes
Using console.log instead of console.error for errors.
Omitting the next parameter.
5fill in blank
hard

Fill all three blanks to create a route that catches synchronous errors and passes them to the error handler.

Express
app.get('/data', (req, res, [1]) => {
  try {
    throw new [2]('Failed to load data');
  } catch (err) {
    [3](err);
  }
});
Drag options to blanks, or click blank then click option'
Anext
BError
Dres
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to call next(err) inside the catch block.
Using res instead of next to forward errors.