Question

I'm having a problem getting the response from a 400 error header with restangular. The code I've written is:

var loginData = Restangular.all("login");
  $scope.postForm = function() {
    loginData.post($scope.formData).then(function(response){
      var error = response.error;

      if(error) {
        $scope.error = response.message;
      } else {
        localStorageService.clearAll();
        localStorageService.set('xxx', response.id);
        localStorageService.set('xxx', response.apiKey);

        $location.path('/main');
      }
    });
  }

When I get back a 200 header the $scope.error gets the response.message but not when the response header is 400. I set up the setErrorInterceptor() to log the message to console but I can't figure out how to get it to return the response so I can set the $scope.header.

Edit: this is how I log the message to console in setErrorInterceptor()

RestangularProvider.setErrorInterceptor(
      function(response) {
        if (response.status == 401) {
          console.log("Login required... ");
          $window.location.href='/login';
        } else if (response.status == 400) {
          console.log(response.data.message);
        } else {
          console.log("Response received with HTTP error code: " + response.status );
        }
        return false; // I also tried commenting return false out
      });
Was it helpful?

Solution

Check How can I handle errors in the FAQ. You need to pass in a second function into the then() method of the promise to act as an error handler.


Restangular.all("accounts").getList().then(function() {
  console.log("All ok");
}, function(response) {
  console.log("Error with status code", response.status);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top