且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript的try-catch在TypeError上失败

更新时间:2023-11-29 14:29:22

当您使用jQuery并且http请求是异步的时,您无法使用try-catch处理此类错误,这只会捕获调用的错误.请求,而不是整个过程.

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.

一些研究给了我这个链接: http://bugs.jquery.com/ticket/8744

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

实际上,当请求超时时,不应调用jsonpCallback函数,它似乎是浏览器错误: https://bugzilla.mozilla.org/show_bug.cgi?id=707154

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

jQuery错误报告中的某人( e.marin.izquierdo )提供了可能解决处理"此错误的方法. (我对它进行了一些更改,删除了不相关的内容)

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);

它会在错误侦听器中创建jsonpCallback以避免发生错误,但是要执行此操作,您需要知道jsonpCallback的名称.

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.

小提琴链接