A custom error class is a user-defined class that extends the built-in Error class to create specific error types with custom properties or messages, helping to handle errors more clearly in Express apps.
Click to reveal answer
beginner
How do you create a basic custom error class in Express?
You create a class that extends Error, call super(message) in the constructor, and optionally add properties like statusCode to represent HTTP error codes.
Click to reveal answer
intermediate
Why add a statusCode property to a custom error class in Express?
Adding statusCode helps middleware know which HTTP status to send in the response, making error responses clear and consistent.
Click to reveal answer
intermediate
What is the benefit of using custom error classes over plain Error objects in Express?
Custom error classes let you distinguish error types easily, add extra info, and handle different errors in specific ways in middleware.
Click to reveal answer
beginner
Show a simple example of a custom NotFoundError class in Express.
A. Constructor should not accept message parameter
B. Status code 401 is invalid for authentication errors
C. Missing call to super(message) in constructor
D. Class should not extend Error for custom errors
Solution
Step 1: Check constructor of subclass of Error
When extending Error, the constructor must call super(message) to properly initialize the error message.
Step 2: Identify missing super call
The code sets this.message directly but does not call super(), which causes errors in Error inheritance.
Final Answer:
Missing call to super(message) in constructor -> Option C
Quick Check:
Always call super(message) in Error subclass constructor [OK]
Hint: Always call super() first in Error subclass constructor [OK]
Common Mistakes:
Setting this.message without super()
Forgetting to extend Error
Using wrong status codes for errors
5. You want to create a custom error class DatabaseError that accepts a message and an optional error code, defaulting to 500. Which implementation correctly supports this and sets both status and code properties?
hard
A. class DatabaseError extends Error {
constructor(message, code = 500) {
super(message);
this.status = code;
this.code = 500;
}
}