Generic error handling in Angular

2019-09-17 10:55发布

问题:

I am using interceptor in my app for generic error handling when service is down I am getting success response with status 200 even i have changed the base url to test my service. What am i doing wrong??

      var myServices = angular.module('myServices', ['ngResource']);

       myServices.config(function ($provide, $httpProvider) {
       $provide.factory('ErrorInterceptor', function ($q) {
       return {
        response: function(){
        return response;// always success??
       }
        responseError: function(rejection) {
        $scope.addErrorAlert("Services are currently not responding.  Please try again later.",true);
            return;
        }
    };
});

回答1:

the best way to add interceptor in $httpProvider is to create a separate factory for that and push the same into $httpProvider.interceptors

var myServices = angular.module('myServices', ['ngResource']);

myServices.factory('ErrorInterceptor', function ($q) {
    return {
        responseError: function (response) {
            return $q.reject(response);
        }
    };

})
myServices.config(function ($httpProvider) {

    $httpProvider.interceptors.push('ErrorInterceptor');

});


回答2:

You can use interceptors to write global exception handler. You just need to override responseError interceptor. Here i called "openErrorModel" method defined on $rootScope to open error model with error message when ever there is error. This would be cleaner and modularized. and you can avoid duplication this way.

Sample code:

(function (global) {
    "use strict";

    angular.module("TestAPp").factory('httpInterceptor', ["$rootScope", "$q", function ($rootScope, $q) {
        return {
        responseError: function (response) {
            /* Open Error model and display error */
            $rootScope.openErrorModel(response);
            /* reject deffered object so that it'll reach error block , else it'll execute success function */
            return $q.reject(response);
        }
        };
    }]);

}(this));

//registering interceprtor

(function (global) {
    "use strict";

    angular.module("TestApp", [])
           .config([ '$httpProvider',function ($httpProvider) {
                /* Register the interceptor */
                $httpProvider.interceptors.push('httpInterceptor');

    }]);

}(this));

PS: My openErrorModel definition

$rootScope.openErrorModel = function (error) {
      $rootScope.errorMessage = error.data;
      $('#errorModal').modal('show');
};

You can refer to Error Handling in angular for more info.