在JavaScript中多次捕获

8 javascript

是否有可能在J中使用多个catch,S(ES5 or ES6)就像我在下面描述的那样(仅作为示例):

try {
­­­­  // just an error
  throw 1; 
}
catch(e if e instanceof ReferenceError) {
­­­­  // here i would like to manage errors which is 'undefined' type
}
catch(e if typeof e === "string") {
  ­­­­// here i can manage all string exeptions
}
// and so on and so on
catch(e) {
  ­­­­// and finally here i can manage another exeptions
}
finally {
­­­­  // and a simple finally block
}
Run Code Online (Sandbox Code Playgroud)

这与我们C#在a或a中的相同Java.

提前致谢!

Dan*_*ite 9

不.在JavaScript或EcmaScript中不存在.

你可以通过if[...else if]...else内部完成同样的事情catch.

根据MDN,有一些非标准实现(并且不在任何标准轨道上).


Leg*_*tin 9

以这种方式尝试:

try {
  throw 1; 
}
catch(e) {
    if (e instanceof ReferenceError) {
       // ReferenceError action here
    } else if (typeof e === "string") {
       // error as a string action here
    } else {
       // General error here
    }
}
finally {}
Run Code Online (Sandbox Code Playgroud)


Gee*_*cks 5

当然,多个 if/then/else 绝对没有错,但我从不喜欢它的外观。我发现当所有东西都排列好时,我的眼睛浏览得更快,所以我改用切换方法来帮助我浏览/寻找正确的块。{}既然 ES6let命令已经流行起来,我也开始使用词法范围来包含 case 块。

try {

  // OOPS!

} catch (error) {

  switch (true) {
    case (error instanceof ForbiddenError): {
      // be mean and gruff; 
      break;
    }
    case (error instanceof UserError): {
      // be nice; 
      break;
    }
    default: {
      // log, cuz this is weird;
    }
  }

}
Run Code Online (Sandbox Code Playgroud)