Reputation: 9184
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.
Upvotes: 16
Views: 3694
Reputation: 2811
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) {
}
Upvotes: 3
Reputation: 9184
so... i have done it so:
if(rejection.config.url.indexOf('?page=') > -1) {
skipException = true;
}
Upvotes: 1
Reputation: 2430
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
Upvotes: 2
Reputation: 419
In the "response" you shoud check response url, not response.config.url.. something like this:
var response = function(response) {
if(response.url.indexOf('?page=') > -1) {
skipException = true;
}
return response;
}
at the response level you don't have the config
Upvotes: 1
Reputation: 620
From the documentation:
A response status code between 200 and 299 is considered a success status and will result in the success callback being called.
Since the server returns a 404, the responseError
function gets called. Unfortunately, the config parameter is not available so you can't do any conditional logic based on the request url in there.
Upvotes: -1