AngularJS Promise 错误捕获

AngularJS Promise error catching

本文关键字:错误 Promise AngularJS      更新时间:2023-09-26

有以下代码:

 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;
} 

这是我的身份验证模块。现在我在控制器中有以下功能:

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";
      });
   };
} 

问题:如果我输入了错误的电子邮件/密码,我正在等待 2 个错误回调 - 从第二个的第一个"然后"开始,但我捕获了第一个错误回调(我可以看到控制台日志),之后成功回调执行!(返回$state.go('allPosts'))。为什么?来自服务器的响应为 401 错误。

这样做的原因是,您在"app.services"中捕获了错误,并且不会将问题"冒泡"到更高的层。

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;
} 

或者完全错过错误处理程序。

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

如果捕获错误并在错误中返回值,则以下承诺不知道发生的错误。

由于身份验证服务返回then函数返回的承诺,因此在第一个错误回调中,您需要返回被拒绝的承诺。

您可以通过以下方式执行此操作:

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(error);   // return a rejected promise;
    });
   };

还要记住将$q注入到服务中,以便正常工作。

then返回的承诺使用成功和错误回调函数的返回值进行解析。如果你做一个标准的回报,你将永远走上成功的道路。当你返回$q.reject时,你返回的承诺最终被拒绝。请参阅有关$q的文档。

还可以从服务中的错误回调引发异常,并获得相同的结果。