0
0
Expressframework~8 mins

Centralized error handler in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Centralized error handler
MEDIUM IMPACT
This affects server response time and user experience by managing errors efficiently without blocking the event loop.
Handling errors in an Express app
Express
app.get('/data', async (req, res, next) => {
  try {
    const result = await database.query('SELECT * FROM table');
    res.send(result);
  } catch (err) {
    next(err);
  }
});

app.use((err, req, res, next) => {
  res.status(500).send('Centralized error: ' + err.message);
});
Centralizes error handling in one middleware, reducing duplication and improving maintainability and response consistency.
📈 Performance GainReduces redundant error checks and improves server response consistency, lowering INP.
Handling errors in an Express app
Express
app.get('/data', (req, res) => {
  database.query('SELECT * FROM table', (err, result) => {
    if (err) {
      res.status(500).send('Error occurred');
      return;
    }
    res.send(result);
  });
});
Error handling is repeated in every route, causing code duplication and potential inconsistent responses.
📉 Performance CostIncreases code size and complexity, slightly increasing server CPU usage and response time.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Repeated inline error handlingN/A (server-side)N/AN/A[X] Bad
Centralized error middlewareN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Errors caught in route handlers are passed to centralized middleware, which sends a response without blocking the event loop.
Request Handling
Response Sending
⚠️ BottleneckError propagation if not handled properly can delay response sending.
Core Web Vital Affected
INP
This affects server response time and user experience by managing errors efficiently without blocking the event loop.
Optimization Tips
1Use a single centralized error middleware to handle all errors.
2Avoid duplicating error handling logic in each route handler.
3Use async/await with try/catch and next() to forward errors efficiently.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a main performance benefit of using a centralized error handler in Express?
AIncreases the number of reflows in the browser
BBlocks the event loop to handle errors synchronously
CReduces code duplication and improves response consistency
DAdds large bundles to the client-side
DevTools: Network
How to check: Open DevTools Network panel, trigger an error route, and inspect response time and status codes.
What to look for: Consistent error status codes and minimal delay in error responses indicate good centralized handling.