V8中相当于SpiderMonkey的catch(e if e..)的语法

3
使用SpiderMonkey,您可以利用条件捕获块将异常路由到适当的处理程序。
try {
// function could throw three exceptions
getCustInfo("Lee", 1234, "lee@netscape.com")
}
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)
}
< p >< em >来自MDN的示例 < p>然而,在V8中,这段代码无法编译。除了显而易见的解决方法之外,还有其他建议或解决方法吗?

1个回答

6

据我所知,在其他JavaScript引擎中没有类似的功能。

但使用这个特性很容易转换代码:

try {
    A
} catch (e if B) {
    C
}

将代码转换为只使用所有JavaScript引擎都支持的标准特性:
try {
    A
} catch (e) {
    if (B) {
        C
    } else {
        throw e;
    }
}

你提供的例子非常容易翻译:
try {
    getCustInfo("Lee", 1234, "lee@netscape.com");
} catch (e) {
    if (e == "InvalidNameException") {
        bad_name_handler(e);
    } else if (e == "InvalidIdException") {
        bad_id_handler(e);
    } else if (e == "InvalidEmailException") {
        bad_email_handler(e);
    } else {
        logError(e);
    }
}

1
那个显而易见的东西,使用switch语句可能会更好,你确定没有类似的实现吗? - Amjad Masad
是的,这是SpiderMonkey中的非标准扩展。 - Jason Orendorff
附注:这不能处理像堆栈跟踪之类的东西,如果您不想捕获某种类型的异常。 - Benjamin Gruenbaum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接