如何捕获JavaScript中的所有http请求错误?

时间:2014-02-26 09:26:01

标签: javascript http dom

最重要的是,英语不好,随意纠正。

有没有办法捕获由DOM引起的所有http请求错误(例如<link><img>等的URL损坏)或JavaScript中的ajax?

我尝试了window.onerror,但它似乎只支持捕获JavaScript运行时错误,不包括http请求错误。

任何想法都表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可以将.ajaxSetup用于正常的http调用,例如:

代码:

$.ajaxSetup({
      cache: false,
      error: function(jqXHR, exception) {
          if (jqXHR.status === 0) {
            //Some code here
          } else if (jqXHR.status == 404) {
            //Some code here
          } else if (jqXHR.status == 500) {
            //Some code here
          } else if (exception === 'parsererror') {
            //Some code here
          } else if (exception === 'timeout') {
            //Some code here
          } else if (exception === 'abort') {
            //Some code here
          } else {
          }
      }
  });

对于像socket.io这样的第三方错误,您需要单独处理它,如:

socket.on('error', function() {
   //here i change options
   socket = io.connect(host, options);

});

相关问题