Handling Specific Error Types
You'll learn how to respond differently to different error classes using instanceof checks in your catch blocks.
When errors occur in async functions, not all problems are the same. A network timeout is different from invalid user input, which differs from a permission error. By checking the type of error caught, you can handle each situation appropriately—retry network errors, prompt users to fix input, or escalate permissions issues.
Using instanceof in Catch Blocks
The instanceof operator tests whether an error is an instance of a specific error class (like TypeError, RangeError, or custom error classes). This lets you branch your error handling logic:
class NetworkError extends Error {
constructor(message) {
super(message);
this.name = 'NetworkError';
}
}
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
async function processData(data) {
try {
if (!data.email) {
throw new ValidationError('Email is required');
}
// Simulate network call
throw new NetworkError('Connection timeout');
} catch (error) {
if (error instanceof ValidationError) {
console.log('User error:', error.message);
// Show form error to user
} else if (error instanceof NetworkError) {
console.log('Network issue:', error.message);
// Retry or show "try again later"
} else {
console.log('Unexpected error:', error);
// Log for debugging
throw error; // Re-throw unknown errors
}
}
}
Think of It Like Sorting Mail
Imagine sorting mail by type: bills go to accounting, invitations to your calendar, junk to recycling. Similarly, instanceof checks sort errors so each gets the appropriate response.
Key Takeaway: Use instanceof in catch blocks to identify specific error types and handle each category with targeted logic—improving user experience and making debugging easier.