Standard for typifying errors/exceptions?

Asked

Viewed 882 times

10

As far as I know, Javascript has no error typing.

In C# and Java, it is possible to do things like:

try {
    /* .. snip .. */
} catch (FooException foo) {
    /* .. snip .. */
} catch (BarException bar) {
    /* .. snip .. */
} catch (NotEnoughCoffeException nec) {
    /* .. snip .. */
} /* etc. */

And so we give a different error treatment for each type of exception.

In javascript, the best we have is:

try {
    /* .. snip .. */
} catch (couldBeAnything) {
    /* dize-me com quem erras e te direi quem és */
}

And what’s worse, it doesn’t even have duck typing to help at this time.

When we have some Javascript code that can fail in several different ways... Is there any design pattern, any methodology to identify what happened? Some way to insert an error code in the exception, for example?

2 answers

12


There are the conditional exceptions (similar to the one you will get in C# 6) which is even more flexible than that, you can filter anything:

try {
    myroutine(); // pode lançar umas das três exceções abaixo
} catch (e if e instanceof TypeError) {
    // código que manipula a exceção TypeError
} catch (e if e instanceof RangeError) {
    // código que manipula a exceção RangeError
} catch (e if e instanceof EvalError) {
    // código que manipula a exceção EvalError
} catch (e) {
    // código que manipula exceções não especificadas
    logMyErrors(e); // passa o obejto da exceção para um manipular
}

I put in the Github for future reference.

In this specific case the check (the condition), which is basically a if normal, is upon the type of exception through the instanceof. Then you capture the exception only if it is an instance of that type specified in if of each catch.

It is not a standard feature and is not available in all Ecmascript implementations, so use at your own risk. And the risk is great. It is not recommended.

You can get result similar standard-form:

try {
    myroutine(); // pode lançar umas das três exceções abaixo
} catch (e) {
    if (e instanceof TypeError) {
       // código que manipula a exceção TypeError
    } else if (e instanceof RangeError) {
       // código que manipula a exceção RangeError
    } else if (e instanceof EvalError) {
       // código que manipula a exceção EvalError
    } else {
       // código que manipula exceções não especificadas
       logMyErrors(e); // passa o obejto da exceção para um manipular
    }
}

Source: MDN

1

For handling errors and exceptions as you exemplified very well in your question, can be seen in this link: Handling of exceptions where it exposes the types of errors and error object constructors.

In my searches you can also find references regarding the exception handling for the windows store that can be viewed at this link :Overall treatment of exceptions

Browser other questions tagged

You are not signed in. Login or sign up in order to post.