How to catch exceptions thrown in callbacks passed to jQuery?

前端 未结 1 1538
北恋
北恋 2021-02-08 06:06

I\'d like to catch exceptions thrown from callbacks passed to jQuery (either to event handlers like click, or to jqXHR methods such as then or al

1条回答
  •  青春惊慌失措
    2021-02-08 06:42

    You can wrap each callback like this:

    function cbWrapper(fn) {
        return function() {
            try {
                return(fn.apply(this, arguments));
            } catch(e) {
                // handle all your exceptions here
            }
        };
    }
    

    So, when you go to pass a callback to an Ajax call, instead of passing the actual callback, you pass cbWrapper(callback).

    $.get(url, cbWrapper(myRealCallback));
    

    Or the inline anonymous version would be like this:

    $.get(url, cbWrapper(function() {
        // actual callback code here
    }));
    

    A more advanced way of doing it would be to override $.get() with your own implementation that wraps the callback automatically, but that gets tricky because jQuery is so flexible about what arguments are actually passed. Because of that and because you have to override one specific argument to make this work, you would have to duplicate all of their argument detection code that figures out which arguments are present and which correspond to which actual function parameters. That code is a bit messy. It's doable and probably won't break because if jQuery broke it, then existing jQuery code would break, but it isn't very clean.

    If it's all your own code, you could just make your own version of $.get() that isn't so flexible with argument positions and switch all of your code to use it instead of the actual $.get():

    jQuery.fn.myGet = function(url, fn) {
        return(jQuery.get(url, cbWrapper(fn)));
    }
    

    0 讨论(0)
提交回复
热议问题