0

What is the purpose of inheriting from the Error class?

An example of inheriting from the Error class is shown.

class InputError extends Error {}

function promptDirection(question) {
  let result = prompt(question);
  if (result.toLowerCase() == "left") return "L";
  if (result.toLowerCase() == "right") return "R";
  throw new InputError("Invalid direction: " + result);
}
for (;;) {
  try {
    let dir = promptDirection("Where?");
    console.log("You chose ", dir);
    break;
  } catch (e) {
    if (e instanceof InputError) {
      console.log("Not a valid direction. Try again.");
    } else {
      throw e;
    }
  }
}

My question is:

What is the purpose of making a new class of InputError? Can't we just use Error instead of InputError?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Yousef
  • 85
  • 6

1 Answers1

1

If you had not extended Error to create a separate InputError class and just thrown a normal Error, then if (e instanceof InputError) would not work.

Of course there are other ways to distinguish errors (such as matching against the error .message, or - safer - on a custom .code property), but building an error hierarchy using subclasses and using instanceof is common and reflects the design used in many other programming languages.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375