Bắt nhiều loại lỗi trong javascript [trùng lặp]
 Aug 16 2020
Nếu tôi xác định các lớp lỗi tùy chỉnh như thế này:
class MyCustom Error extends Error{ }
Làm cách nào để tôi có thể mắc nhiều lỗi như sau:
try{
  if(something)
    throw MyCustomError();
  if(something_else)
    throw Error('lalala');
}catch(MyCustomError err){
 
}catch(err){
}
?
Đoạn mã trên không hoạt động và có một số lỗi cú pháp
Trả lời
1  TheOtterlord Aug 16 2020 at 15:37
Tài liệu MDN khuyến nghị sử dụng một if/elsekhối bên trong catchcâu lệnh. Điều này là do không thể có nhiều catchcâu lệnh và bạn không thể bắt lỗi cụ thể theo cách đó.
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 được gõ yếu. Sử dụng if (err instanceof MyCustomError)bên trong mệnh đề bắt.