如何處理HTTP錯誤500,當使用AngularJS「http get then」構造(承諾)?在AngularJS中處理錯誤http然後構造
$http.get(url).then(
function(response) {
console.log('get',response)
}
)
問題是,對於任何非200 HTTP響應,不調用內部函數。
如何處理HTTP錯誤500,當使用AngularJS「http get then」構造(承諾)?在AngularJS中處理錯誤http然後構造
$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).success(successCallback).error(errorCallback);
更換successCallback和errorCallback與功能。
編輯:考慮到他正在使用then
,Laurent的回答更爲正確。然而,我將這裏留下來作爲參觀這個問題的人們的替代選擇。
值得一提的是,這與洛朗的答案並不一樣。 '.then()'返回一個承諾。 '.success()'和'.error()'不。 –
@ james-brewer:爲了更加準確,'.then()'返回一個** new ** promise。 '.success()'和'.error()'不會,它們都返回'get(url)'提供的原始承諾。 – dod
請務必記住,$ http api的'success'和'error'回調將被棄用。 –
如果你想在全球範圍內處理服務器錯誤,您可能需要爲$ httpProvider註冊一個攔截器服務:
$httpProvider.interceptors.push(function ($q) {
return {
'responseError': function (rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
您可以通過使用更清潔該位:
$http.get(url)
.then(function (response) {
console.log('get',response)
})
.catch(function (data) {
// Handle error here
});
與@ this.lau_ answer類似,採用不同的方法。
我完全想要這個解決方案。 – charliebrownie
它必須被接受的答案,因爲'.error()'方法不適用於500錯誤!請接受。 – saike
在v1.6.0中刪除'success'&'remove'後的最佳解決方案 –
試試這個
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);
}
}
還要注意的是上面的 '響應' 對象有:數據,狀態,頭,配置,狀態文本。上面的'data'對象有:data,status,config,statusText。 (有關是否傳遞statusText的特殊規則 - 瀏覽器,移動與否,Web服務器等) – OzBob
另請注意:'data.config.url'包含完整的** url + params ** ,以防您通過參數旁邊的網址 –