Equivalencia de V8 de la captura de SpiderMonkey (e if e ..)

Using SpiderMonkey you can utilize 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)
}

example from MDN

However in V8 this code wont compile, any suggestions, or work arounds other than the obvious.

preguntado el 08 de enero de 11 a las 18:01

1 Respuestas

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

Respondido el 08 de enero de 11 a las 21:01

Will that the obvious thing, a switch statement maybe even better, your sure there is no similar implementations? - Amjad Masad

Yes. It's a nonstandard extension in SpiderMonkey. - Jason Orendorff

Side Note: this does not handle things like stack traces if you want to not catch an exception of a certain type. - Benjamin Gruenbaum

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.