Reputation: 4679
How can I handle an HTTP error, e.g. 500, when using the AngularJS "http get then" construct (promises)?
$http.get(url).then(
function(response) {
console.log('get',response)
}
)
Problem is, for any non 200 HTTP response, the inner function is not called.
Upvotes: 67
Views: 119011
Reputation: 35478
$http.get(url).success(successCallback).error(errorCallback);
Replace successCallback and errorCallback with your functions.
Edit: Laurent's answer is more correct considering he is using then
. Yet I'm leaving this here as an alternative for the folks who will visit this question.
Upvotes: 14
Reputation: 38177
I could not really work with the above. So this might help someone.
$http.get(url)
.then(
function(response) {
console.log('get',response)
}
).catch(
function(response) {
console.log('return code: ' + response.status);
}
)
See also the $http response
parameter.
Upvotes: 1
Reputation: 1271
Try this
function sendRequest(method, url, payload, done){
var datatype = (method === "JSONP")? "jsonp" : "json";
$http({
method: method,
url: url,
dataType: datatype,
data: payload || {},
cache: true,
timeout: 1000 * 60 * 10
}).then(
function(res){
done(null, res.data); // server response
},
function(res){
responseHandler(res, done);
}
);
}
function responseHandler(res, done){
switch(res.status){
default: done(res.status + ": " + res.statusText);
}
}
Upvotes: 3
Reputation: 2421
You can make this bit more cleaner by using:
$http.get(url)
.then(function (response) {
console.log('get',response)
})
.catch(function (data) {
// Handle error here
});
Similar to @this.lau_ answer, different approach.
Upvotes: 59
Reputation: 38378
If you want to handle server errors globally, you may want to register an interceptor service for $httpProvider:
$httpProvider.interceptors.push(function ($q) {
return {
'responseError': function (rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
Docs: http://docs.angularjs.org/api/ng.$http
Upvotes: 4
Reputation: 90766
You need to add an additional parameter:
$http.get(url).then(
function(response) {
console.log('get',response)
},
function(data) {
// Handle error here
})
Upvotes: 148