V8's equivalence of SpiderMonkey's catch(e if e..)
Using SpiderMonkey you can utilize conditional catch blocks to route exceptions to the appropriate handl开发者_如何学Goer.
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)
}
example from MDN
However in V8 this code wont compile, any suggestions, or work arounds other than the obvious.
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:
try {
A
} catch (e if B) {
C
}
into code that just uses standard features that all the JavaScript engines support:
try {
A
} catch (e) {
if (B) {
C
} else {
throw e;
}
}
The example you gave is even easier to translate:
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);
}
}
精彩评论