Sikau

Advanced JavaScript · Day 24 · about 25 min

Designing errors

Custom error classes and causes.

Errors are part of your API

"Something went wrong" helps nobody. Good errors say what kind of problem happened and keep the original cause, so the code that catches them can react properly — retry a network error, show a form message for a validation error.

Custom error classes

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

function signUp(email) {
  if (!email.includes("@")) throw new ValidationError("email", "That email looks incomplete");
  return "ok";
}

try {
  signUp("ashaexample.com");
} catch (err) {
  if (err instanceof ValidationError) console.log(`${err.field}: ${err.message}`);
  else throw err;
}

The rest of this lesson

  • Keeping the causeexplain
  • Catch what you can handleexplain
  • Predict the outputpredict
  • instanceof chainpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript