JavaScript › Error Handling

How do you create a custom error class?

Intermediate

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.

Common follow-ups: Why do you need to explicitly set this.name in a custom error subclass?