Forrest Keppler Forrest Keppler - 1 month ago 7
HTTP Question

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?

Answer

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