V8 SpiderMonkey catch equivalence (e, if e ..)

Using SpiderMonkey, you can use conditional catch blocks to route exceptions to the appropriate handler.

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)
}

MDN example

However, in V8 this code will not compile, nor any suggestions, nor work around, except for the obvious.

+3
source share
1 answer

As I know, there is no such function in other JavaScript machines.

But using this function, it's easy to convert the code:

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

to code that simply uses standard functions supported by all JavaScript mechanisms:

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);
    }
}
+6
source

Source: https://habr.com/ru/post/1784289/


All Articles