问题
Im sending a form to nodejs for authentication. Using $http.get
in the following function and adding a promise
> .then
. In production, does this handle all the errors that I may get from the server? Do I need to add anything else to this function?
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");
}
});
}
});
As always, many thanks!
回答1:
Your function only handles successful server responses like 200, but it doesn't account for server exceptions 500 or authorized errors 401, etc. For those you need to provide catch callback:
$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');
})
回答2:
I would add the second callback to your .then
, which is the error handler.
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!
});
}
});
来源:https://stackoverflow.com/questions/42988661/angular-http-get-how-to-catch-all-the-errors