typestar

Custom errors in JavaScript

Subclassing Error to carry structured failure data.

class ValidationError extends Error {
  constructor(field) {
    super(`invalid field: ${field}`);
    this.name = "ValidationError";
    this.field = field;
  }
}

function validate(user) {
  if (!user.email) throw new ValidationError("email");
  return user;
}

try {
  validate({});
} catch (error) {
  if (error instanceof ValidationError) console.warn(error.field);
  else throw error;
}

How it works

  1. extends Error and super(message) set up the class.
  2. Extra fields like field travel with the error.
  3. instanceof distinguishes it; re-throw the rest.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
366
Tokens
92
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 1 of 2 in Errors, step 38 of 43 in Language basics.

← Previous Next →