Background
Controller
authService.login(email, password)
.success(function (response) {
/* go to application */
})
.error(function (response) {
/* display proper error message */
});
auth Service
factory.login = function(email, password) {
return $http({
method: 'POST',
url: "http://myserver/user/authenticate",
data: $.param({email: email, password: password}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
Problem
When username and password fails and API returns 400 response, even though I'm catching the error and I'm displaying a proper message to user, the error appears in browser console.
POST http://myserver/user/authenticate 400 (Bad Request)
Can I handle errors in a better way?
Try this
factory.login = function(email, password) {
return $http({
method: 'POST',
url: "http://myserver/user/authenticate",
data: $.param({email: email, password: password}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
/**Check here your status code 400 if you found that status code is 400 the reject the promise**/
if (statuscode !==400) {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function (response) {
// something went wrong
return $q.reject(response);
});
}
and then use following code
authService.login(email, password)
.then(function (response) {
/* go to application */
},function(error) {
console.log(error); /* catch 400 Error here */
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With