Javascript: exception and error strategy

Does anyone know a good exception and error handling strategy. Right now I have different pieces of code handling their own check / error / exception, but I would really have a centralized strategy. I was thinking of some kind of global notification system that passes some errors / exceptions to the user, such as checking. Other errors that I could post in my back-end and register them.

For example, a validation error may contain the element that caused the error. That way I can add a class to highlight it and add text before or after.

So, if anyone has concrete examples of how to do this, I would really appreciate it.

+3
source share
2 answers

If it's worth it, you can customize the errors and build a function around them that contains the default behavior:

function errorHandler() {

    var error = arguments[1] ; //!! pass the error
    /* additional arguments */

    var errorCode = error.message ;

    var errorMap = { //!! a map that matches error codes to default behaviour
        "customErrorName":function() {
            /* default behaviour for this kind of error */
        } ,
        /* more custom error codes and default behaviour */
    }

        if(errorCode in errorMap) { //!! error code has a default behaviour
            errorMap[ errorCode ]() ; //!! call default behaviour
        } else {
            /* log unknown error */
        }

}

You would do this in a block try { ... } catch(e) { ... }:

try {
    /* your code */
    if(someErrorCondition) {
        throw new Error("someError") ;
    }
} catch(e) {
    errorHandler(e) ;
}

There are also default errors in javascript. Here is the list in the following link: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Error

+2
source

If your main problem is with validation, I think the most specific way to do this is to use the jQuery validation plugin which is really customizable and has a good base for you to start handling exceptions.

catch catch javascript, , , .

0

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


All Articles