2014-02-26 54 views
0

首先,英语不好,随时纠正。如何捕捉JavaScript中的所有http请求错误?

有什么办法可以捕获由DOM导致的所有http请求错误(例如,破损的URL为<link><img>等)或JavaScript中的ajax?

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

任何想法表示赞赏。

+0

为什么不尝试使用调试工具,如萤火虫! – tnanoba

+0

@crypticous,因为我想收集这些错误并将它们发送到客户端上的服务器。 – Jerry

+0

您的Web服务器通常会保留它生成的404的日志 –

回答

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

});

+0

'.ajaxError()'更直截了当 –