Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Promise error catching

There is the following code:

 angular.module('app.services', []).factory('authService', [
'SIGN_IN_ENDPOINT', 'SIGN_OUT_ENDPOINT', '$http', '$cookieStore', function(SIGN_IN_ENDPOINT, SIGN_OUT_ENDPOINT, $http, $cookieStore) {
  var auth;
  auth = {};
  auth.signIn = function(credentials) {
    return $http.post(SIGN_IN_ENDPOINT, {
      user: credentials
    }).then(function(response, status) {
       return $cookieStore.put('user', response.data);
    }, function(error) {
       return console.log("Incorrect email/password");
    });
   };
  return auth;
} 

This is my module for authentication. Now I have the following function in controller:

angular.module('app.admin.controllers', []).controller('SignInController', [
  '$scope', 'authService', '$state', function($scope, authService, $state) {
    $scope.buttonText = "Login";
    return $scope.login = function() {
      $scope.buttonText = "Logging in. . .";
      return authService.signIn($scope.credentials).then(function(response, status) {
        return $state.go('allPosts');
      }, function(err) {
        $scope.invalidLogin = true;
        return $scope.buttonText = "Login";
      });
   };
} 

The problem: if I input wrong email/password, I'm waiting for 2 error callbacks - from the first 'then' from the second one, but I catch the first error callback (I can see console log) and after it THE SUCCESS callback executes! (return $state.go('allPosts')). Why? The Response from the server is 401 error.

like image 502
malcoauri Avatar asked Jul 22 '26 12:07

malcoauri


1 Answers

The reason for this is, that you catch the error in the "app.services" and dont "bubble" the problem to higher tiers.

angular.module('app.services', []).factory('authService', [
'SIGN_IN_ENDPOINT', 'SIGN_OUT_ENDPOINT', '$http', '$cookieStore', function(SIGN_IN_ENDPOINT, SIGN_OUT_ENDPOINT, $http, $cookieStore) {
  var auth;
  auth = {};
  auth.signIn = function(credentials) {
    return $http.post(SIGN_IN_ENDPOINT, {
      user: credentials
    }).then(function(response, status) {
       return $cookieStore.put('user', response.data);
    }, function(error) {
       console.log("Incorrect email/password");
       return $q.reject();  //here is the important one.
    });
   };
  return auth;
} 

Or completely miss out the error handler.

auth.signIn = function(credentials) {
        return $http.post(SIGN_IN_ENDPOINT, {
          user: credentials
        }).then(function(response, status) {
           return $cookieStore.put('user', response.data);
        });
       };

If you catch the error and return a value within the error, following promises dont know about the occured error.

like image 62
Konstantin Krass Avatar answered Jul 25 '26 01:07

Konstantin Krass