Course contentsShow
← JavaScript
Lesson 1157 of 2,72326. Error HandlingFree lesson

Hierarchies of Error Classes

Creating error class hierarchies for domain-specific errors like ValidationError extending AppError.

Hierarchies of Error Classes

You'll learn how to build multi-level error class hierarchies to organize domain-specific errors in maintainable ways.

Why Error Hierarchies Matter

Just as you might have a general "Animal" class with specific types like "Dog" and "Cat," you can create a hierarchy of error classes. This lets you organize errors by domain and catch them at different levels of specificity.

Think of it like a family tree: you might have a base AppError class for all your application errors, then specialized children like ValidationError, AuthenticationError, or DatabaseError. Each child can have its own children too—for example, EmailValidationError and PasswordValidationError extending ValidationError.

Building a Hierarchy

// Base application error
class AppError extends Error {
  constructor(message) {
    super(message);
    this.name = 'AppError';
    this.isOperational = true;
  }
}

// Domain-specific error
class ValidationError extends AppError {
  constructor(message, field) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

// More specific error
class EmailValidationError extends ValidationError {
  constructor(email) {
    super(`Invalid email: ${email}`, 'email');
    this.name = 'EmailValidationError';
    this.email = email;
  }
}

Using the Hierarchy

try {
  throw new EmailValidationError('bad@email');
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(`Field ${error.field} failed validation`);
  }
  if (error instanceof AppError) {
    console.log('This is our application error');
  }
}

The hierarchy lets you catch errors broadly or specifically, depending on your needs.

Key Takeaway: Error class hierarchies organize related errors into parent-child relationships, enabling flexible error handling at different levels of specificity—catch broadly with parent classes or precisely with specific error types.