Bird
Raised Fist0
Expressframework~20 mins

Async error handling in routes in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Async Error Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when an async route throws an error without next()?

Consider this Express route handler using async/await:

app.get('/data', async (req, res) => {
  const data = await fetchData();
  if (!data) throw new Error('No data found');
  res.json(data);
});

What will Express do if fetchData() returns null causing the error to be thrown?

AThe request will hang and eventually time out without a response.
BThe server will crash because the error is unhandled.
CExpress will catch the error and send a 500 response automatically.
DExpress will send a 404 Not Found response.
Attempts:
2 left
💡 Hint

Think about how Express handles errors in async functions without calling next().

📝 Syntax
intermediate
2:00remaining
Which option correctly passes async errors to Express error handler?

Given an async route, which code snippet correctly forwards errors to Express's error middleware?

A
app.get('/user', async (req, res, next) => {
  try {
    const user = await getUser();
    if (!user) throw new Error('User not found');
    res.json(user);
  } catch (err) {
    next(err);
  }
});
B
app.get('/user', (req, res, next) => {
  getUser().then(user => {
    if (!user) throw new Error('User not found');
    res.json(user);
  }).catch(next);
});
C
app.get('/user', async (req, res, next) => {
  const user = await getUser();
  if (!user) throw new Error('User not found');
  res.json(user);
});
D
app.get('/user', async (req, res) => {
  try {
    const user = await getUser();
    if (!user) throw new Error('User not found');
    res.json(user);
  } catch (err) {
    res.status(500).send(err.message);
  }
});
Attempts:
2 left
💡 Hint

Look for the option that uses next(err) inside a try/catch block.

🔧 Debug
advanced
2:00remaining
Why does this async error handler not catch errors?

Examine this Express route:

app.get('/items', async (req, res, next) => {
  fetchItems().then(items => {
    if (!items) throw new Error('No items');
    res.json(items);
  });
});

Why won't errors thrown inside then() be caught by Express's error handler?

ABecause Express only catches errors thrown synchronously, not inside promises.
BBecause the async function does not await the promise, errors inside then() are unhandled.
CBecause the route handler is missing the next parameter.
DBecause fetchItems() is not returning a promise.
Attempts:
2 left
💡 Hint

Consider how async functions and promises interact with error propagation.

🧠 Conceptual
advanced
2:00remaining
What is the benefit of using a wrapper function for async route handlers?

Why do many Express apps use a wrapper like const wrap = fn => (req, res, next) => fn(req, res, next).catch(next); around async route handlers?

AIt converts async functions into synchronous ones.
BIt improves performance by caching route responses.
CIt prevents the route handler from running multiple times.
DIt automatically catches errors from async functions and forwards them to Express error middleware.
Attempts:
2 left
💡 Hint

Think about how error handling is simplified with this pattern.

❓ state_output
expert
2:00remaining
What is the response status and body when an async route calls next() with an error?

Given this Express setup:

app.get('/fail', async (req, res, next) => {
  try {
    await Promise.reject(new Error('Failed'));
  } catch (err) {
    next(err);
  }
});

app.use((err, req, res, next) => {
  res.status(400).json({ error: err.message });
});

What will the client receive when requesting /fail?

AStatus 500 with empty response body
BStatus 200 with JSON body {"error":"Failed"}
CStatus 400 with JSON body {"error":"Failed"}
DNo response, request times out
Attempts:
2 left
💡 Hint

Look at the error middleware and the status code it sets.

Practice

(1/5)
1. What is the main reason to use try/catch blocks inside async route handlers in Express?
easy
A. To automatically retry failed requests
B. To catch errors from asynchronous code and pass them to Express error handlers
C. To make the route handler run faster
D. To prevent the server from starting

Solution

  1. Step 1: Understand async errors in Express routes

    Async functions can throw errors that are not caught automatically by Express, so we need to catch them manually.
  2. Step 2: Use try/catch to handle errors

    Wrapping async code in try/catch allows catching errors and passing them to Express with next(error).
  3. Final Answer:

    To catch errors from asynchronous code and pass them to Express error handlers -> Option B
  4. Quick Check:

    try/catch in async routes = catch async errors [OK]
Hint: Use try/catch to catch async errors and call next(error) [OK]
Common Mistakes:
  • Ignoring errors in async functions
  • Not calling next(error) inside catch
  • Assuming Express catches async errors automatically
2. Which of the following is the correct syntax to pass an error to the next middleware in an async Express route?
easy
A. res.send(error)
B. throw error
C. return error
D. next(error)

Solution

  1. Step 1: Identify how Express handles errors

    Express expects errors to be passed to the next middleware using next(error).
  2. Step 2: Confirm correct syntax in async routes

    Inside a catch block, calling next(error) forwards the error to the error handler middleware.
  3. Final Answer:

    next(error) -> Option D
  4. Quick Check:

    Pass errors with next(error) [OK]
Hint: Use next(error) to forward errors in Express [OK]
Common Mistakes:
  • Using throw instead of next(error) inside async catch
  • Returning error instead of passing to next
  • Sending error directly with res.send inside catch
3. Consider this Express route handler:
app.get('/data', async (req, res, next) => {
  try {
    const result = await fetchData();
    res.json(result);
  } catch (error) {
    next(error);
  }
});

What happens if fetchData() throws an error?
medium
A. The error is caught and passed to the next error handler middleware
B. The server crashes immediately
C. The request hangs without response
D. The error is ignored and response is sent anyway

Solution

  1. Step 1: Analyze the try/catch block

    If fetchData() throws, the catch block runs and calls next(error).
  2. Step 2: Understand Express error flow

    Calling next(error) sends the error to Express error handler middleware, preventing crashes or hanging.
  3. Final Answer:

    The error is caught and passed to the next error handler middleware -> Option A
  4. Quick Check:

    Errors in try/catch + next(error) = handled error [OK]
Hint: Errors in async try/catch go to next(error) middleware [OK]
Common Mistakes:
  • Assuming server crashes on async error
  • Thinking response is sent despite error
  • Not using next(error) to handle errors
4. Identify the error in this async Express route handler:
app.get('/user', async (req, res, next) => {
  const user = await getUser();
  res.json(user);
});

What is the problem with this code regarding error handling?
medium
A. It sends response twice
B. It incorrectly uses next() inside the route
C. It lacks a try/catch block to handle errors from the async function
D. It uses synchronous code inside async function

Solution

  1. Step 1: Check for error handling in async code

    The async function getUser() might throw errors, but no try/catch is used.
  2. Step 2: Understand Express error propagation

    Without try/catch and calling next(error), errors will not be handled properly and may crash the server.
  3. Final Answer:

    It lacks a try/catch block to handle errors from the async function -> Option C
  4. Quick Check:

    Async routes need try/catch for error handling [OK]
Hint: Always wrap async code in try/catch to handle errors [OK]
Common Mistakes:
  • Omitting try/catch in async route handlers
  • Expecting Express to catch async errors automatically
  • Not calling next(error) inside catch
5. You want to create a centralized error handler middleware in Express that catches all errors passed by next(error). Which of the following is the correct way to define this middleware?
hard
A. app.use((err, req, res, next) => { res.status(500).json({ message: err.message }); });
B. app.use((req, res, next) => { res.status(500).send('Error'); });
C. app.get('/error', (err, req, res) => { res.send(err); });
D. app.use((err, req, res) => { res.json({ error: err }); });

Solution

  1. Step 1: Recall Express error handler signature

    Error handlers must have four parameters: (err, req, res, next).
  2. Step 2: Check each option for correct signature and response

    app.use((err, req, res, next) => { res.status(500).json({ message: err.message }); }); uses all four parameters and sends JSON with error message and status 500, which is correct.
  3. Final Answer:

    app.use((err, req, res, next) => { res.status(500).json({ message: err.message }); }); -> Option A
  4. Quick Check:

    Error handler middleware = 4 params + send error response [OK]
Hint: Error middleware needs 4 params: err, req, res, next [OK]
Common Mistakes:
  • Missing the 'next' parameter in error middleware
  • Using app.get instead of app.use for error handler
  • Not setting status code in error response
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard