admin管理员组文章数量:1135134
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.
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.
Share Improve this question edited Jun 15, 2017 at 11:23 laurent 90.7k82 gold badges307 silver badges440 bronze badges asked Jun 13, 2013 at 5:58 Federico EllesFederico Elles 4,6797 gold badges28 silver badges35 bronze badges6 Answers
Reset to default 148You need to add an additional parameter:
$http.get(url).then(
function(response) {
console.log('get',response)
},
function(data) {
// Handle error here
})
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.
https://docs.angularjs.org/api/ng/service/$http
$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.
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
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);
}
}
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.
本文标签: javascriptError handling in AngularJS http get then constructStack Overflow
版权声明:本文标题:javascript - Error handling in AngularJS http get then construct - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736908829a1956070.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论