JavaScript's try-catch is failing on typeerror

江枫思渺然 提交于 2019-12-24 17:20:56

问题


Just saw this error today on our application. We have a small box on top right of the webpage. It gets updated every minute. What it does is make a jsonp call to each of our hospital partners via intranet and pulls the latest news. The issue doesn't happen often. I actually found out why the error is happening.

Uncaught TypeError: jQuery11020382352269484832883_1441911920555 is not a function

This error shows up in console when a jsonp request doesn't get the response from the jsonp service within the time assigned on the jsonp timeout.

I wrapped our endpoint call with try-catch but it is still spitting out that error. I want to get rid of "Uncaught TypeError" and display our own custom error.


回答1:


As you use jQuery and an http request is async, you cannot handle this kind of error with a try-catch, this would catch only errors for the call of the request, not the entire process.

Some research gave me this link : http://bugs.jquery.com/ticket/8744

Actually the jsonpCallback function should not be called when the request timeout, it appear to be a browser bug : http://bugs.jquery.com/ticket/8744#comment:2 https://bugzilla.mozilla.org/show_bug.cgi?id=707154

Someone in the jQuery bug repport (e.marin.izquierdo) gave a possible solution to "handle" this error. (I changed it a little bit removing irrelevant stuff)

var auxTime = new Date();
var jQueryCallbackRandom = auxTime.getTime();

var callParameters = {
    url: 'http://jsfiddle.net/echo/jsonp/',
    timeout: 5,
    dataType: "jsonp",
    data: { echo: "Hello World!" },
    jsonpCallback: "jQueryRandom_" + jQueryCallbackRandom,
    success: function(){
        console.log("success");   
    },
    error: function(jqXHR, textStatus){
        console.log("failed with error: " + textStatus);
        window["jQueryRandom_" + jQueryCallbackRandom] = function() {
            window["jQueryRandom_" + jQueryCallbackRandom] = null;
        };
    }       
};

$.ajax(callParameters);

It create the jsonpCallback in the error listener to avoid the error, but to do this you need to know the name of the jsonpCallback.

Fiddle link



来源:https://stackoverflow.com/questions/32515179/javascripts-try-catch-is-failing-on-typeerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!