0

In my current situation, I'm using an $http interceptor to catch response errors and display a simple message to let the user know something went wrong. But now I want to make a difference between errors that came from requests that are sent during the loading of a page or requests that are sent due to an action of the user itself (f.e. pressing a button, entering a field ...).

Example of the $httpInterceptor I want to have:

return {
   responseError: function (response) {
      // IF THE REQUEST IS FROM A PAGE LOAD
         // DO SOMETHING
      // IF THE REQUEST IS NOT FROM A PAGE LOAD
         // DO SOMETHING ELSE
      return $q.reject(response);
   }
};

To make it a bit more clear:

CASE 1: A user is waiting for a page to load:

  • REQ 1 is sent
  • REQ 2 is sent
  • REQ 3 is sent
    • REQ 4 is sent after response of REQ 3
      • REQ 5 is sent after response of REQ 4
  • REQ 6 is sent
    • REQ 7 is sent after response of REQ 6

All the requests above are part of the page load and if one of them returns an error, it should have a specific behavior.

Requests that are triggered not because of a page load:

CASE 2: User presses a button:

  • REQ 1 is sent
    • REQ 2 is sent after response of REQ 1

These requests are not part of the page load and in case of an error should act differently.

Is there any way I can somehow make a difference between these 2 cases? As my project is quite large, I don't want to change the code of every $http request to identify it is from a page load or not, so that is not a solution for me.

  • Check out this link https://stackoverflow.com/questions/4231580/get-if-browser-is-busy – Nicolas Jul 21 '17 at 14:46
  • Define what do you mean with page loada, (partials html, and other assets?). If i uderstand you whant to catch exceptions with some decorate message when templates loading and fails, and other when comes from some kind of api im i right ? – Jesus Carrasco Jul 21 '17 at 14:55

1 Answers1

0

You can create some kind or regular expression, and testing if came from desire url and make choices.

.service('RequestsInterceptor', [
'$q',
function(
  $q,
  ) {
    var UNAUTHORIZED_CODE = 401;
    var FORBIDDEN_CODE = 403;
    var NOTFOUND_CODE = 404;
    var INTERNAL_ERROR = 500;

        this.request = function(config) {
            //logic to send
            return config || $q.when(config);
        };
        this.responseError = function(rejection) {

            console.log(rejection.config.url)

            var apiPattern = /\/api\//;

            if(apiPattern.test(rejection.config.url)) {
                //do your logic when url are api
            }else{
              //do your logic when url are templates
            }
            return $q.reject(rejection);
        };
    }
]);
Jesus Carrasco
  • 1,355
  • 1
  • 11
  • 15