Advertisement
Intermediate JavaScript, Error Handling

How do you create a custom error class?

Short answer

Extend the built-in Error class, call super(message) in the constructor to set up the message and stack trace, then add any extra properties specific to your error type.

Save JavaScript mock interview
Advertisement
AModel answer
Extend the built-in Error class, call super(message) in the constructor to set up the message and stack trace, then add any extra properties specific to your error type.
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}
throw new ValidationError('Required', 'email');
Real-world example
Distinguishing a ValidationError from a NetworkError in a catch block to show different UI messages.
Likely follow-ups
  • Why do you need to explicitly set this.name in a custom error subclass?
Related topics