How to catch HTTP error response in Angular

Background

  • An Angular application communicates with the database through a set of API endpoints.
  • user / authenticate endpoints accept a username and password and return a successful response (200) or a bad request response (400).

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 the username and password fail and the API returns 400 responses, even if I catch the error and I show the correct message to the user, the error appears in the browser console.

 POST http://myserver/user/authenticate 400 (Bad Request) 

Is it possible to handle errors better?

+5
source share
1 answer

try it

 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 the following code

  authService.login(email, password) .then(function (response) { /* go to application */ },function(error) { console.log(error); /* catch 400 Error here */ }); 
+4
source

All Articles