【问题标题】:Catch multiple types of errors in javascript [duplicate]在javascript中捕获多种类型的错误[重复]
【发布时间】:2020-12-05 20:56:38
【问题描述】:

如果我这样定义自定义错误类:

class MyCustom Error extends Error{ }

我怎样才能捕捉到这样的多个错误:

try{

  if(something)
    throw MyCustomError();

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


}catch(MyCustomError err){
 

}catch(err){

}

?

上面的代码不起作用并给出了一些语法错误

【问题讨论】:

    标签: javascript node.js error-handling


    【解决方案1】:

    MDN docs 建议在 catch 语句中使用 if/else 块。这是因为不可能有多个 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
      }
    }
    

    【讨论】:

      【解决方案2】:

      JavaScript 是弱类型的。在 catch 子句中使用if (err instanceof MyCustomError)

      【讨论】:

      • 请注意,在 JavaScript 中不可能有多个 catch,并且 IE 不支持 if catch 子句。
      猜你喜欢
      • 2017-01-13
      • 2020-12-11
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2016-08-12
      • 2019-02-20
      • 2020-09-13
      相关资源
      最近更新 更多