本文介绍了JavaScript的try-catch在TypeError上失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在我们的应用程序上看到了此错误.我们在网页右上方有一个小方框.它每分钟更新一次.它的作用是通过Intranet向我们的每个医院合作伙伴进行jsonp调用,并获取最新消息.这个问题并不经常发生.实际上,我发现了错误发生的原因.

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

当在jsonp超时所分配的时间内jsonp请求未从jsonp服务获得响应时,此错误会在控制台中显示.

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.

我用try-catch封装了端点调用,但它仍会吐出该错误.我想摆脱未捕获的TypeError"并显示我们自己的自定义错误.

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.

推荐答案

当您使用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函数,它似乎是浏览器错误: http://bugs.jquery.com/ticket/8744#comment:2 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.

小提琴链接

这篇关于JavaScript的try-catch在TypeError上失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 10:39