Angular $ http.get: How to catch all errors?
Im submitting a nodejs form for authentication. Using $http.get
in the following function and adding promise
> .then
. In production, does it handle all the errors I can get from the server? Do I need to add anything else to this feature?
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");
}
});
}
});
Thanks a lot as always!
+3
source to share
2 answers
Your function only handles successful server responses like 200, but does not account for 500 server exceptions or resolved 401 errors, etc. For those who need to provide a 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');
})
+3
source to share
I would add a second callback to yours .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!
});
}
});
+2
source to share