Performance: Async error handling in routes
This affects server response time and user experience by managing asynchronous errors efficiently without blocking the event loop.
app.get('/data', async (req, res, next) => { try { const data = await fetchData(); res.send(data); } catch (err) { next(err); } });
app.get('/data', async (req, res) => { const data = await fetchData(); res.send(data); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No async error handling | N/A | N/A | N/A | [X] Bad |
| Try-catch with next() in async route | N/A | N/A | N/A | [OK] Good |
try/catch blocks inside async route handlers in Express?next(error).next(error).next(error) forwards the error to the error handler middleware.app.get('/data', async (req, res, next) => {
try {
const result = await fetchData();
res.json(result);
} catch (error) {
next(error);
}
});fetchData() throws an error?fetchData() throws, the catch block runs and calls next(error).next(error) sends the error to Express error handler middleware, preventing crashes or hanging.app.get('/user', async (req, res, next) => {
const user = await getUser();
res.json(user);
});getUser() might throw errors, but no try/catch is used.next(error), errors will not be handled properly and may crash the server.next(error). Which of the following is the correct way to define this middleware?(err, req, res, next).Pass the test and this pattern moves unknown