5

If I define custom error classes like this:

class MyCustom Error extends Error{ }

How can I catch multiple errors like this:

try{

  if(something)
    throw MyCustomError();

  if(something_else)
    throw Error('lalala');


}catch(MyCustomError err){
 

}catch(err){

}

?

The code above does not work and gives some syntax error

0

2 Answers 2

8

The MDN docs recommends using an if/else block inside the catch statement. This is because it is impossible to have multiple catch statements and you cannot catch specific errors in that way.

try {
  myroutine(); // may throw three types of exceptions
} catch (e) {
  if (e instanceof TypeError) {
    // statements to handle TypeError exceptions
  } else if (e instanceof RangeError) {
    // statements to handle RangeError exceptions
  } else if (e instanceof EvalError) {
    // statements to handle EvalError exceptions
  } else {
    // statements to handle any unspecified exceptions
    logMyErrors(e); // pass exception object to error handler
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

JavaScript is weakly typed. Use if (err instanceof MyCustomError) inside the catch clause.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.