I have an issue with angularjs app communicating with a REST API. The problem is the api returnes a status code and also adds a status description like HTTP/1.1 417 Invalid quantity. With jquery ajax the jqXHR object had a statusText property but with angularjs I can't seem to find how can I access this in my error handler. Needless to say I can't modify the API which for a 417 status code for example can return different status descriptions. I have found that I would need to change the angularjs library but in case of an update this would not be handy. I would have to change xhr.responseText to xhr.statusText. Can I somehow overwrite this function from my code and don't modify angular library?
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
completeRequest(
callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders());
}
};
You need to create an httpInterceptor as outlined here during your module config.
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q) {
return function(promise) {
return promise.then(function(response) {
// do something on success
}, function(response) {
//do something for your 417 error
if(response.status == 417) {
alert("We've got a 417!");
return $q.reject(response);
}
//some other error
return $q.reject(response);
});
}
});
$httpProvider.responseInterceptors.push('myHttpInterceptor');
The support for statusText was added in AngularJS 1.2.16.
Here's the work around to get StatusText (as pointed out that some mobile browsers strip out DATA from successfull responses: http://stackoverflow.com/a/28470163/1586498
I have also discovered that .success and .error on $http in Angular does not pass the StatusText, you have to use .then(response)