0
0
Node.jsframework~8 mins

Error-handling middleware in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: Error-handling middleware
MEDIUM IMPACT
This affects server response time and user experience by managing errors efficiently during request processing.
Handling errors in an Express.js application
Node.js
app.get('/data', (req, res, next) => {
  try {
    throw new Error('Failed to load data');
  } catch (err) {
    next(err);
  }
});

app.use((err, req, res, next) => {
  res.status(500).json({ error: err.message });
});
Catches errors and sends a controlled response without crashing, keeping server responsive.
📈 Performance GainPrevents server crash and response blocking; maintains fast error response.
Handling errors in an Express.js application
Node.js
app.use((req, res, next) => {
  // no error handling middleware
  next();
});

app.get('/data', (req, res) => {
  throw new Error('Failed to load data');
});
No error-handling middleware means thrown errors crash the server or cause unhandled promise rejections, blocking responses.
📉 Performance CostBlocks response, causing slow or no reply; may crash server leading to downtime.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No error-handling middlewareN/A (server-side)N/AN/A[X] Bad
Proper error-handling middlewareN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Error-handling middleware intercepts errors during request processing and sends a response without blocking the event loop.
Request Handling
Response Generation
⚠️ BottleneckBlocking the event loop due to unhandled errors
Core Web Vital Affected
INP
This affects server response time and user experience by managing errors efficiently during request processing.
Optimization Tips
1Always use centralized error-handling middleware to catch errors.
2Avoid throwing errors without catching them to prevent server crashes.
3Respond quickly with error messages to keep user experience smooth.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using error-handling middleware in Node.js?
AIt improves CSS rendering speed in the browser.
BIt reduces the size of the JavaScript bundle sent to clients.
CIt prevents server crashes and keeps responses fast.
DIt decreases the number of DOM nodes created.
DevTools: Network
How to check: Open DevTools Network tab, trigger a request that causes an error, and observe the response status and body.
What to look for: Look for HTTP 500 or other error status with a JSON error message instead of a stalled or no response.