I have set up a separate server for my angularjs app, which is different from my grunt server. This external server runs on Apache and uses PHP to serve JSON data. I want to be able to catch any potential server errors, ranging from "server down" to "404".
I attempted to utilize interceptors in the following manner:
app.factory('myFactory', function($resource) {
return $resource('http://www.remote.server.com/api/WRONGPATH',
});
app.config(function ($routeProvider, $httpProvider) {
...
$httpProvider.responseInterceptors.push(function($q) {
return function(promise) {
return promise.then(function(successResponse) {
if (successResponse.config.method.toUpperCase() !== 'GET') {
console.info('success');
}
return successResponse;
}, function(errorResponse) {
switch (errorResponse.status) {
case 401:
console.info('wrong usename or password');
break;
case 403:
console.info('no rights to do this');
break;
case 500:
console.info('server internal error: ' + errorResponse.data);
break;
default:
console.info('error ' + errorResponse.status + ': ' + errorResponse.data);
}
return $q.reject(errorResponse);
});
};
});
});
Unfortunately, I was not successful with this approach as I always end up in the 'default' case, where errorResponse.status == 0
.
I suspect that this is due to browsers stopping when encountering a CORS error...
However, everything works perfectly if I switch the remote URL to a local one...
Is there a way to handle errors from remote requests made by angular.js $resource (or $http)?
I am open to suggestions for a design change, such as restructuring my PHP service to work more like grunt... (currently, my PHP service simply outputs a JSON list of image names from a server folder...).