×

javascript · level 3 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

classes tell different problems apart.

One plain Error for everything forces you to read messages to work out what went wrong. Instead, make a custom error: a class that extends Error, sets its own name, and can carry extra data such as the field that failed.

Then catch can sort problems with instanceof. Handle the ones you expect, like bad user input. Anything else, such as a typo in your own code, you with throw error, so a real bug is never quietly swallowed.

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}
function checkEmail(email) {
  if (!email.includes("@")) { throw new ValidationError("email", "needs an @"); }
}
try {
  checkEmail("sam.example.com");
} catch (error) { console.log(error instanceof ValidationError, `${error.field} ${error.message}`); }

With no extra data, the short form works too: class NotFoundError extends Error { name = "NotFoundError"; }.