简体   繁体   中英

Catch an error anywhere angularjs

I'm working on an Angularjs app that frequently communicates with a server. I've been tasked with implementing security, when there wasn't any before.

This means that I've changed all the server side api calls to return a 403-unauthorized http status code when the user attempts to perform an action they aren't allowed to perform.

Now, I COULD go and hunt down every single API call that the app makes to the server, and call a function that handles the same error the same way in each one. But I would rather find some way to say "Any time this page gets a 403-unauthorized response, do this function." Is what I'm asking possible?

You can use $http interceptors. By adding an interceptor, you will be able to intercept the response to check the status code and do whatever you want before the original requiring gets notified.

Angularjs $http docs

For example:

app.config(function ($httpProvider) {
  // it can be added by a explicit factory declaration
  // angular.module(...).factory('myHttpInterceptor', function ...
  $httpProvider.interceptors.push(function($q, $state) {
    return {
      'request': function(config) {
        return config;
      },

      'response': function(response) {
        if(response.statusCode === 403){
          $state.go('my.unauthorized.state');
          // or maybe 
          // $rootScope.$broadcast('unauthorized');
        }
        return response;
      }
    };
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM