Reputation: 3444
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!
Upvotes: 3
Views: 2008
Reputation: 21762
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!
});
}
});
Upvotes: 2
Reputation: 193301
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');
})
Upvotes: 3