Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS: custom 404 interceptor handle - response with url

In my app I use an interceptor to catch all http response errors, like:

var response = function(response) {
  if(response.config.url.indexOf('?page=') > -1) {
    skipException = true;
  }
  return response;
}

var responseError = function(rejection) {
  if (rejection.status === 401 || rejection.status === 403) {
    /**/
  }
  else if (rejection.status >= 500 || rejection.status === 0) {
    /**/
  }
  else if (rejection.status === 404 && !skipException) {
    /**/
  }
  else if (rejection.status === 404 && skipException) {
    /**/
  }
  else{
    /**/
  }
  return $q.reject(rejection);
};

And when I go to my controller (when my getArticles method returns some data, not 404 - when articles array is empty) all is OK: 404 with skipException == true is caught.

But when my articles array is empty the server returns a 404 and when I enter this controller I cannot get response.config.url -- no response is caught, but why? I thought that interceptor would catch all of the responses.

    $timeout(function() {
      $scope.getArticles();
    }, 100);

and $scope.getArticles has such code:

getDataService.getArticles($scope.pageNum).then(function(response) {
 /**/
});

service:

var getEventsByScrollService = function(num) {
  var deferred = $q.defer();
  $http.get(***, {

    })
    .success(function(response) {
      deferred.resolve(response);
    }).error(function(err, status) {
      if (status === 404){
        deferred.resolve([]);
      }
      else{
        deferred.reject(err);
      }
    });
  return deferred.promise;
};

How can I conditionally catch 404's depending on the URL? Because this:

if(response.config.url.indexOf('?page=') > -1) { 

Doesn't always work.

like image 442
brabertaser19 Avatar asked Mar 13 '15 08:03

brabertaser19


2 Answers

In an effort to be more maintainable and extendable to any $http service call one could do this:

// Service call
$http.get({url:'/?page=', ignoreErrors: true})

// Interceptor
if(rejection.status === 404 && !rejection.config.ignoreErrors) {

}
like image 94
Cory Silva Avatar answered Nov 08 '22 17:11

Cory Silva


you can check out Restangular, might be useful for your purposes. It has good interceptor methods built in. Whether it's really good for you will depend on if you're using a RESTful API or not. https://github.com/mgonto/restangular

like image 2
BIU Avatar answered Nov 08 '22 17:11

BIU