0
0
Expressframework~10 mins

Async error handling in routes 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 async route handler in Express.

Express
app.get('/data', async (req, res) => { const data = await fetchData(); res.send(data); });

app.get('/async', [1] (req, res) => { const result = await getResult(); res.json(result); });
Drag options to blanks, or click blank then click option'
Afunction
Bawait
Casync
Dcallback
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to add 'async' before the function causes syntax errors when using await.
Using 'await' outside an async function.
2fill in blank
medium

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

Express
app.get('/user', async (req, res) => {
  try {
    const user = await getUser(req.params.id);
    res.json(user);
  } catch ([1]) {
    res.status(500).send('Error fetching user');
  }
});
Drag options to blanks, or click blank then click option'
Aerror
Be
Cerr
Dexception
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving the catch parameter empty causes syntax errors.
Using a variable name not declared in the catch block.
3fill in blank
hard

Fix the error in this async route by adding the missing error handler call.

Express
app.get('/items', async (req, res, next) => {
  const items = await fetchItems();
  res.json(items);
  [1]
});
Drag options to blanks, or click blank then click option'
Areturn
Bthrow new Error()
Cnext(error)
Dnext()
Attempts:
3 left
💡 Hint
Common Mistakes
Not calling next() causes the request to hang.
Throwing errors without try-catch in async routes causes unhandled promise rejections.
4fill in blank
hard

Fill both blanks to create an async route that forwards errors to Express error middleware.

Express
app.get('/profile', async (req, res, [1]) => {
  try {
    const profile = await getProfile(req.user.id);
    res.json(profile);
  } catch ([2]) {
    next(error);
  }
});
Drag options to blanks, or click blank then click option'
Anext
Berr
Cerror
Dcallback
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter names for next or error causes runtime errors.
Not calling next(error) inside catch blocks prevents error middleware from running.
5fill in blank
hard

Fill all three blanks to create a reusable async error wrapper for Express routes.

Express
const asyncHandler = (fn) => (req, res, [1]) => {
  Promise.resolve(fn(req, res, next)).catch([2]);
};

app.get('/orders', asyncHandler(async (req, res) => {
  const orders = await getOrders();
  res.json(orders);
}));
Drag options to blanks, or click blank then click option'
Anext
Berror
Derr
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent variable names for next or error.
Not returning the Promise causes unhandled errors.