【问题标题】:Generic Ajax Error Handling - interceptor in Angular JS通用 Ajax 错误处理 - Angular JS 中的拦截器
【发布时间】:2016-08-30 23:32:31
【问题描述】:

我想在我的 Angular Js Application 中实现 Ajax 调用的全局错误处理。我认为 $httpprovider 仅适用于 $http 请求。请指导我实现这一目标。我如何编写拦截器来捕获 Ajax 调用的失败。我的主要目标是将 Ajax 调用的失败捕获到谷歌分析中。

【问题讨论】:

    标签: javascript angularjs error-handling


    【解决方案1】:

    在 javascripts try-catch 中编写 ajax 调用

    http://www.w3schools.com/js/js_errors.asp
    

    【讨论】:

    • 我有多个 REST API 可以使用。所以我想在全球范围内这样做,并且不想在每个 catch 块中编写捕获函数
    【解决方案2】:

    你可以尝试监听window.onerror事件但是它会捕获所有的js错误,所以你需要过滤它们。

    window.onerror = function(msg, url, line, col, error) {
       // Note that col & error are new to the HTML 5 spec and may not be 
       // supported in every browser.  It worked for me in Chrome.
       var extra = !col ? '' : '\ncolumn: ' + col;
       extra += !error ? '' : '\nerror: ' + error;
    
       // You can view the information in an alert to see things working like this:
       alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
    
       // TODO: Report this error via ajax so you can keep track
       //       of what pages have JS issues
    
       var suppressErrorAlert = true;
       // If you return true, then error alerts (like in older versions of 
       // Internet Explorer) will be suppressed.
       return suppressErrorAlert;
    };
    

    您可以在this question 中阅读更多相关信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-20
      • 2018-11-04
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多