Custom Error Classes

Custom error classes allow applications to distinguish categories of failures. Extending Error allows code to use instanceof or other properties to make decisions without parsing human-readable messages.

For example, a REST API might distinguish validation errors, authentication errors, and infrastructure errors.

Custom Validation Error
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

throw new ValidationError('Email is required', 'email');
💡 A custom error class carries structured domain information while retaining normal Error behavior.
Key Takeaways
  • Custom errors make error categories explicit.
  • Structured error properties are better than parsing messages.
  • Error classes can be checked using instanceof.
Knowledge Check

What is a major benefit of custom Error classes?