Intermediate LevelExpress JS
How do you design a hierarchical AppError / HttpError class hierarchy for clean error throwing in Express?
❓ Interview Prompt: Explain custom Error classes, HTTP status codes, operational errors vs programmer bugs, and uniform error handlers.
Throwing plain 'new Error("msg")' instances lacks HTTP status code context.
Custom 'AppError' Hierarchy:
Build a base 'AppError' class extending JavaScript's 'Error', adding 'statusCode' and 'isOperational' flags. Create specialized subclasses ('NotFoundError', 'UnauthorizedError', 'BadRequestError') for clean throwing in controllers!
Code Implementation Example
javascript
export class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.isOperational = true; // Distinguishes operational errors from system bugs
}
}
export class NotFoundError extends AppError {
constructor(message = 'Resource Not Found') {
super(message, 404);
}
}
// In Controller: throw new NotFoundError('User #42 not found');💡Designing custom AppError and NotFoundError exception classes.
🎯 Interview Key Takeaway
Create a custom AppError class with statusCode properties to throw structured operational errors in controllers.
#AppError#Error Handling#Exceptions#Intermediate
Back to all Express JS Questions→