在使用 AngularJS “http get then” 构造(承诺)时,如何处理 HTTP 错误,例如 500?
$http.get(url).then(
function(response) {
console.log('get',response)
}
)
问题是,对于任何非 200 HTTP 响应,都不会调用内部函数。
在使用 AngularJS “http get then” 构造(承诺)时,如何处理 HTTP 错误,例如 500?
$http.get(url).then(
function(response) {
console.log('get',response)
}
)
问题是,对于任何非 200 HTTP 响应,都不会调用内部函数。
您需要添加一个附加参数:
$http.get(url).then(
function(response) {
console.log('get',response)
},
function(data) {
// Handle error here
})
您可以使用以下方法使这更清洁:
$http.get(url)
.then(function (response) {
console.log('get',response)
})
.catch(function (data) {
// Handle error here
});
类似于@this.lau_ 答案,不同的方法。
$http.get(url).success(successCallback).error(errorCallback);
将 successCallback 和 errorCallback 替换为您的函数。
编辑:考虑到他使用的是 Laurent,他的回答更正确then
。然而,我将把它留在这里,作为将访问这个问题的人们的替代方案。
如果你想全局处理服务器错误,你可能需要为 $httpProvider 注册一个拦截器服务:
$httpProvider.interceptors.push(function ($q) {
return {
'responseError': function (rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
尝试这个
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);
}
}
我无法真正使用上述内容。所以这可能会帮助某人。
$http.get(url)
.then(
function(response) {
console.log('get',response)
}
).catch(
function(response) {
console.log('return code: ' + response.status);
}
)