0
0
Expressframework~8 mins

Async error handling in routes in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Async error handling in routes
MEDIUM IMPACT
This affects server response time and user experience by managing asynchronous errors efficiently without blocking the event loop.
Handling errors in asynchronous route handlers
Express
app.get('/data', async (req, res, next) => {
  try {
    const data = await fetchData();
    res.send(data);
  } catch (err) {
    next(err);
  }
});
Catches async errors and passes them to Express error middleware, preventing event loop blocking.
📈 Performance GainAvoids blocking event loop, improves response time and server stability.
Handling errors in asynchronous route handlers
Express
app.get('/data', async (req, res) => {
  const data = await fetchData();
  res.send(data);
});
If fetchData() throws an error, it is unhandled and crashes the server or causes hanging requests.
📉 Performance CostBlocks event loop on unhandled rejection, causing delayed or no response.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No async error handlingN/AN/AN/A[X] Bad
Try-catch with next() in async routeN/AN/AN/A[OK] Good
Rendering Pipeline
Async error handling in routes affects the server's event loop and response lifecycle, ensuring errors do not block or delay responses.
Event Loop
Request Handling
Response Sending
⚠️ BottleneckUnhandled async errors block the event loop causing delayed or failed responses.
Core Web Vital Affected
INP
This affects server response time and user experience by managing asynchronous errors efficiently without blocking the event loop.
Optimization Tips
1Always use try-catch blocks in async route handlers to catch errors.
2Pass errors to next() to use Express error middleware for centralized handling.
3Avoid unhandled promise rejections to keep the event loop free and responsive.
Performance Quiz - 3 Questions
Test your performance knowledge
What happens if an async route handler throws an error without a try-catch block?
AThe server may crash or the request hangs due to unhandled promise rejection.
BThe error is automatically caught and logged by Express.
CThe response is sent with a default success message.
DThe browser retries the request automatically.
DevTools: Network
How to check: Open DevTools Network panel, trigger the route, and check if the response is delayed or missing due to errors.
What to look for: Look for hanging requests or 500 errors indicating unhandled async errors.