Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch http error response in Angular

Background

  • My Angular application communicates with a database through a set of API endpoints.
  • "user/authenticate" endpoints accepts username and password and returns a success (200) or a bad request (400) http response.

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?

like image 773
user2364656 Avatar asked Jul 18 '15 04:07

user2364656


1 Answers

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 */
    });
like image 130
user1608841 Avatar answered Oct 01 '22 20:10

user1608841