ตรวจจับข้อผิดพลาดหลายประเภทในจาวาสคริปต์ [ซ้ำ]

Aug 16 2020

หากฉันกำหนดคลาสข้อผิดพลาดที่กำหนดเองเช่นนี้:

class MyCustom Error extends Error{ }

ฉันจะตรวจจับข้อผิดพลาดหลายรายการเช่นนี้ได้อย่างไร:

try{

  if(something)
    throw MyCustomError();

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


}catch(MyCustomError err){
 

}catch(err){

}

เหรอ?

โค้ดด้านบนไม่ทำงานและมีข้อผิดพลาดทางไวยากรณ์บางประการ

คำตอบ

1 TheOtterlord Aug 16 2020 at 15:37

เอกสาร MDNแนะนำการใช้if/elseบล็อกภายในcatchคำสั่ง เนื่องจากเป็นไปไม่ได้ที่จะมีหลายcatchคำสั่งและคุณไม่สามารถตรวจจับข้อผิดพลาดเฉพาะในลักษณะนั้นได้

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

จาวาสคริปต์พิมพ์ผิด ใช้if (err instanceof MyCustomError)ภายในคำสั่ง catch