Default to typify errors / exceptions?

8

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 handling 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, you do not have to duck typing to help at that time.

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

    
asked by anonymous 25.09.2014 / 18:26

2 answers

11

There are conditional exceptions (similar to what you'll get in C # 6) that's even more flexible than this, 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 placed it on GitHub for future reference.

In this particular case the check (condition), which is basically a if normal, is on top of the exception type through instanceof . So you catch 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 implementations of EcmaScript, so use at your own risk. And the risk is great. It's not recommended.

You can get similar result by default:

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

    
25.09.2014 / 18:31
1

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

In my searches you can also find references regarding exception handling for windows store that can be viewed at this link: Global exception handling

    
25.09.2014 / 18:39