V8 与 SpiderMonkey 的 catch(e if e..) 的等价
使用 SpiderMonkey,您可以利用条件 catch 块将异常路由到适当的处理程序。
try {
// function could throw three exceptions
getCustInfo("Lee", 1234, "[email protected]")
}
catch (e if e == "InvalidNameException") {
// call handler for invalid names
bad_name_handler(e)
}
catch (e if e == "InvalidIdException") {
// call handler for invalid ids
bad_id_handler(e)
}
catch (e if e == "InvalidEmailException") {
// call handler for invalid email addresses
bad_email_handler(e)
}
catch (e){
// don't know what to do, but log it
logError(e)
}
来自 MDN 的示例
但是,在 V8 中,此代码无法编译,任何建议或除显而易见的解决方案之外的解决方案都无法编译。
Using SpiderMonkey you can utilize conditional catch blocks to route exceptions to the appropriate handler.
try {
// function could throw three exceptions
getCustInfo("Lee", 1234, "[email protected]")
}
catch (e if e == "InvalidNameException") {
// call handler for invalid names
bad_name_handler(e)
}
catch (e if e == "InvalidIdException") {
// call handler for invalid ids
bad_id_handler(e)
}
catch (e if e == "InvalidEmailException") {
// call handler for invalid email addresses
bad_email_handler(e)
}
catch (e){
// don't know what to do, but log it
logError(e)
}
example from MDN
However in V8 this code wont compile, any suggestions, or work arounds other than the obvious.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,其他 JavaScript 引擎没有类似的功能。
但是使用此功能很容易将代码转换
为仅使用所有 JavaScript 引擎支持的标准功能的代码:
您给出的示例更容易翻译:
There's no similar feature in the other JavaScript engines as far as I know.
But it is easy to convert code using this feature:
into code that just uses standard features that all the JavaScript engines support:
The example you gave is even easier to translate: