[英]Angular $http.get: How to catch all the errors?
我發送一個表單到nodejs進行身份驗證。 在以下函數中使用$http.get
並添加promise
> .then
。 在生產中,這是否處理了我可能從服務器獲得的所有錯誤? 我需要在此功能中添加其他內容嗎?
MyApp.controller("Login", function($scope, $http){
$scope.checkuser = function(user){
$http.get('/login', user).then(function(response){
if(response.data){
console.log(response.data);
//based on response.data create if else ..
} else {
console.log("nothing returned");
}
});
}
});
一如既往,非常感謝!
您的函數只處理成功的服務器響應,如200,但它不考慮服務器異常500或授權錯誤401等。對於那些您需要提供catch回調:
$http.get('/login', user)
.then(function(response) {
if (response.data) {
console.log(response.data);
//based on response.data create if else ..
} else {
console.log("nothing returned");
}
})
.catch(function() {
// handle error
console.log('error occurred');
})
我會將第二個回調添加到你的.then
,這是錯誤處理程序。
MyApp.controller("Login", function($scope, $http){
$scope.checkuser = function(user){
$http.get('/login', user).then(function(response){
if(response.data){
console.log(response.data);
//based on response.data create if else ..
} else {
console.log("nothing returned");
}
}, function(error){
//THIS IS YOUR ERROR HANDLER. DO ERROR THINGS IN HERE!
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.