Extending the Error Class
You'll learn how to create specialized error types by extending JavaScript's built-in Error class using class syntax.
Core Idea
Just as you can create custom classes for your application objects, you can create custom error classes by extending the built-in Error class. This gives you specialized error types with additional properties or behaviors while maintaining all the standard error features like stack traces and error messages.
Think of it like creating different types of alerts in a security system. A basic alarm works, but having specific types (fire alarm, burglar alarm, flood alarm) helps you respond appropriately to each situation.
How It Works
You use the class syntax with the extends keyword to inherit from Error. Inside your custom class constructor, you must call super() to invoke the parent Error constructor, passing the error message. You should also set the name property to match your custom class name for better debugging.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
// Now you can throw and catch your custom error
try {
throw new ValidationError("Invalid email format");
} catch (error) {
console.log(error.name); // "ValidationError"
console.log(error.message); // "Invalid email format"
console.log(error instanceof Error); // true
}
Your custom error class inherits everything from Error (like message and stack), but you can add custom properties or methods specific to your application's needs.
Key Takeaway: Extending the Error class with class syntax and proper super() calls creates specialized error types that maintain full error functionality while allowing you to add custom behavior and properties.