Retry request with $http interceptor

Here’s a $http interceptor that (immediately) replays timed out request(s) (i.e. response status 0). There were two non-obvious (to me!) elements to constructing this example:

  1. How to call $http from within the interceptor – simply adding $http to the dependency list didn’t work as angular complains of a circular dependency
  2. How to reference the original request from the response object in order to retry it

This answer addresses both topics but is more involved so I include a simplified version below.

joinApp.factory('httpResponseErrorInterceptor',function($q, $injector) {
  return {
    'responseError': function(response) {
      if (response.status === 0) {
        // should retry
        var $http = $injector.get('$http');
        return $http(response.config);
      }
      // give up
      return $q.reject(response);
    }
  };
});

joinApp.config(function($httpProvider) {
  $httpProvider.interceptors.push('httpResponseErrorInterceptor');
});

In your actual implementation, you would likely want more sophisticated http response code processing, a limit to the number of times you retry, etc.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)