devwannabe
devwannabe

Reputation: 3210

JavaScript's try-catch is failing on typeerror

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.

Upvotes: 1

Views: 2254

Answers (1)

Hacketo
Hacketo

Reputation: 4997

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

Upvotes: 1

Related Questions