【问题标题】:Handle angular http errors using interceptors使用拦截器处理 Angular http 错误
【发布时间】:2016-09-20 10:36:45
【问题描述】:

我的问题是处理来自 http REST 调用的错误的最佳方法是什么。我应该使用拦截器还是装饰器?我的休息功能看起来像这样:

    queryFunction : function (config) {
    var defer = $q.defer();
    var config = {};
    $http.get(someUrl, config) //or http.put, delete
      .then(function (response) {
        defer.resolve(response.data);
      })
      .catch(function (ex) {
        defer.reject(ex);
      });
    return defer.promise;
    },

最简单的拦截器会是什么样子?

【问题讨论】:

    标签: angularjs error-handling interceptor angular-http-interceptors


    【解决方案1】:

    这是通用 $http ErrorInterceptor 的代码:

      app.factory('ErrorInterceptor', ['$q', function($q) {
        return {
            responseError: function(rejection) {
                // An error message is shown for all kind of server errors
                if (rejection.status == -1) {
                //alert('Backend is not working');
                //use rejection.data variable 
                }
                return $q.reject(rejection);
             }
         };
       }])
    

    然后它可以包含在应用配置中

    app.config(['$httpProvider', function($httpProvider) {
      $httpProvider.interceptors.push('ErrorInterceptor');
    })
    

    【讨论】:

    • 谢谢,这是我正在寻找的答案。
    • 您能否为上面的代码发布通用 jasmine 单元测试?
    • 如果有人需要回答我自己的问题,请使用:'code "use strict"; describe('ErrorInterceptor', function() { var ErrorInterceptor; var httpProviderIt; beforeEach(function() { module('moduleName', function ($httpProvider) { //保存我们的拦截器 httpProviderIt = $httpProvider; }); inject(function (ErrorInterceptor) { ErrorInterceptor = ErrorInterceptor; console.log(ErrorInterceptor); }); }); it('应该定义 ErrorInterceptor', function () { expect (ErrorInterceptor).toBeDefined(); }); });'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2018-11-04
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多