Search code examples
javascriptajaxjsonpstaledataexception

How to receive notification on 404,409 and other server errors on jsonp call


I have this jsonp function:

    function jsonp(url, callback) {
    var script = document.createElement("script");
    script.setAttribute("type","text/javascript");
    script.setAttribute("onerror","javascript:DisplayPopUp('','staleExceptionRefresh')");
    script.setAttribute("src", url + questionMark + "accept=jsonp&callback="+callback + "&cachebuster="+new Date().getTime());
    document.getElementsByTagName("head")[0].appendChild(script);
}

I catch the success event like this:

function someCallbackFunction(data1, data2) {}

but the problem is that if I get 404 or 409 or some other server errors I don't know how to catch them (they do not appear on someCallbackFunction).

I can set an onerror attribute to display something but how do I catch the server's response.

this is an example for a server response that I am not able to catch with my regular callback function:

DeleteWebsiteAjaxCall({"action":"", "type":"", "callerId":""}, {errorDescription: "important description I want to display","success":false,"payload":null});

How do I catch these errors (stale exceptions?!) on a function?


Solution

  • function jsonp(url, callback) {
        var script = document.createElement("script");
        script.setAttribute("type","text/javascript");
        script.setAttribute("src", url + questionMark + "accept=jsonp&callback="+callback + "&cachebuster="+new Date().getTime());
        var errHandler = function(evt) {
          clearTimeout(timer)
          // reference to http://www.quirksmode.org/dom/events/error.html
          // you will get an error eventually, and you can call callback manually here, to acknowledge it.
          // but unfortunately, on firefox you can get error type as undefined, and no further detail like error code on other browser either. 
          // And you can tell the callback function there is a net error (as no other error will fire this event.)
          window[callback](new Error());
        };
        script.onerror = errHandler;
        script.onload = function() {
          clearTimeout(timer);
        }
        // also setup a timeout in case the onerror failed.
        document.getElementsByTagName("head")[0].appendChild(script);
        var timer = setTimeout(errHandler, 5000);
    }
    

    If your server will response when 404/409 happens, then send the 200 status code to client instead to make the script being evaluated.

    Otherwise, the browser will omit the server response and fire onerror event.