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

Alex
  • 66,732
  • 177
  • 439
  • 641

2 Answers2

7

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
  }
}
The Otterlord
  • 1,680
  • 10
  • 20
1

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

Hi - I love SO
  • 615
  • 3
  • 14