0
0
Expressframework~8 mins

Custom error classes in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Custom error classes
MEDIUM IMPACT
This affects server response time and error handling efficiency, impacting how quickly errors are processed and sent to clients.
Handling errors in Express middleware
Express
class NotFoundError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NotFoundError';
    this.status = 404;
  }
}

app.use((req, res, next) => {
  try {
    // some code
  } catch (err) {
    next(err);
  }
});
Custom error classes provide clear error types and properties, reducing runtime checks and improving error handling clarity.
📈 Performance GainReduces error type checking overhead and improves debugging speed.
Handling errors in Express middleware
Express
app.use((req, res, next) => {
  try {
    // some code
  } catch (err) {
    err.status = 500;
    next(err);
  }
});
Modifying generic Error objects on the fly can cause inconsistent error properties and extra processing to check error types.
📉 Performance CostAdds minor overhead in error property checks and can cause unclear error stack traces.
Performance Comparison
PatternError Object CreationType CheckingStack Trace ClarityVerdict
Modifying generic Error objects dynamicallyLow costHigh cost due to repeated checksUnclear or inconsistent[X] Bad
Using custom error classes with fixed propertiesLow costLow cost with instanceof checksClear and consistent[OK] Good
Rendering Pipeline
In Express, error handling affects the server response pipeline by determining how errors propagate and how responses are generated.
Error Creation
Middleware Execution
Response Sending
⚠️ BottleneckMiddleware Execution when error types are checked repeatedly or error properties are modified dynamically.
Optimization Tips
1Use custom error classes to standardize error properties and types.
2Avoid modifying generic Error objects dynamically during error handling.
3Custom error classes improve debugging clarity and reduce runtime overhead.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance benefit of using custom error classes in Express?
ABlocks the event loop during error creation
BIncreases bundle size significantly
CReduces runtime error type checking overhead
DTriggers multiple reflows in the browser
DevTools: Node.js Inspector (Debugger)
How to check: Run your Express app with --inspect flag, set breakpoints in error middleware, and observe error objects and stack traces.
What to look for: Check error object types and properties to confirm custom error classes are used and stack traces are clear.