Type-Checking Custom Errors
What you'll learn: How to use instanceof to identify and handle specific custom error types in catch blocks.
When you create custom error classes (by extending Error), you often want to respond differently depending on which error occurred. The instanceof operator lets you check whether a caught error is an instance of a particular custom error class, enabling precise, targeted error handling.
Why Type-Checking Matters
Imagine you're sorting mail: personal letters need one response, bills need another, and junk mail gets discarded. Similarly, different errors require different handling strategies. A ValidationError might mean showing a user-friendly message, while a DatabaseError might trigger a retry mechanism.
Using instanceof in Catch Blocks
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
class DatabaseError extends Error {
constructor(message) {
super(message);
this.name = 'DatabaseError';
}
}
try {
throw new ValidationError('Invalid email format');
} catch (error) {
if (error instanceof ValidationError) {
console.log('User input error:', error.message);
} else if (error instanceof DatabaseError) {
console.log('Retry database operation');
} else {
console.log('Unknown error:', error);
}
}
The instanceof check returns true when the error was created from that specific class (or a subclass of it). This lets you branch your error-handling logic cleanly.
Multiple Error Types
try {
// code that might throw various errors
} catch (error) {
if (error instanceof ValidationError) {
// handle validation errors
} else if (error instanceof DatabaseError) {
// handle database errors
} else {
// handle all other errors
}
}
Key Takeaway: Use instanceof in catch blocks to identify which custom error type was thrown, enabling specific handling logic for each error class you've defined.