Catch multiple types of errors in javascript

Viewed 2875

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

2 Answers

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
  }
}

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

Related