如何处理HTTP错误,例如500,当使用AngularJS“http get then”构造(promises)?
$http.get(url).then(
function(response) {
console.log('get',response)
}
)
问题是,对于任何非200 HTTP响应,都不会调用内部函数。
答案 0 :(得分:138)
您需要添加其他参数:
$http.get(url).then(
function(response) {
console.log('get',response)
},
function(data) {
// Handle error here
})
答案 1 :(得分:51)
使用以下方法可以使这一点更清晰:
$http.get(url)
.then(function (response) {
console.log('get',response)
})
.catch(function (data) {
// Handle error here
});
与@ this.lau_回答类似,采用不同的方式。
答案 2 :(得分:13)
$http.get(url).success(successCallback).error(errorCallback);
将successCallback和errorCallback替换为您的函数。
编辑:考虑到他正在使用then
,Laurent的答案更为正确。然而,我将离开这里作为将访问这个问题的人的替代方案。
答案 3 :(得分:3)
如果要全局处理服务器错误,可能需要为$ httpProvider注册拦截器服务:
$httpProvider.interceptors.push(function ($q) {
return {
'responseError': function (rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
答案 4 :(得分:2)
试试这个
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);
}
}
答案 5 :(得分:0)
我不能真的使用上面的方法。因此,这可能会对某人有所帮助。
$http.get(url)
.then(
function(response) {
console.log('get',response)
}
).catch(
function(response) {
console.log('return code: ' + response.status);
}
)