ajax - How to catch http error response in Angular -


background

  • my angular application communicates database through set of api endpoints.
  • "user/authenticate" endpoints accepts username , password , returns success (200) or bad request (400) http response.

controller

authservice.login(email, password)     .success(function (response) {         /* go 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 , password fails , api returns 400 response, though i'm catching error , i'm displaying proper message user, error appears in browser console.

post http://myserver/user/authenticate 400 (bad request) 

can handle errors in 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 status code 400 if found status code 400 reject promise**/             if (statuscode !==400) {                         return response.data;                     } else {                         // invalid response                         return $q.reject(response.data);                     }          }, function (response) {             // went wrong             return $q.reject(response);         }); } 

and use following code

 authservice.login(email, password)         .then(function (response) {             /* go application */         },function(error) {                 console.log(error); /* catch 400  error here */     }); 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -