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.
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) {
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With