Wykryj wiele rodzajów błędów w javascript [duplikat]

Aug 16 2020

Jeśli zdefiniuję niestandardowe klasy błędów w ten sposób:

class MyCustom Error extends Error{ }

Jak mogę wychwycić wiele takich błędów:

try{

  if(something)
    throw MyCustomError();

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


}catch(MyCustomError err){
 

}catch(err){

}

?

Powyższy kod nie działa i powoduje błąd składni

Odpowiedzi

1 TheOtterlord Aug 16 2020 at 15:37

Dokumentacja MDN zaleca użycie if/elsebloku wewnątrz catchinstrukcji. Dzieje się tak, ponieważ nie można mieć wielu catchinstrukcji i nie można w ten sposób wychwycić określonych błędów.

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
  }
}
1 Hi-IloveSO Aug 16 2020 at 15:38

JavaScript jest napisany słabo. Użyj if (err instanceof MyCustomError)wewnątrz klauzuli catch.