即使服务 returns 404,$http promise 也会执行成功块

$http promise executes success block even when service returns 404

我很困惑或者可能不明白 angular promise 是如何工作的。我正在尝试为我的错误处理编写一些代码块,但我发现它总是在我的控制器中执行成功块。但是,我也在我的服务中编写了成功和错误块,因为我需要在响应中进行一些转换。我看到它在服务中执行错误块,这非常好,但同样的承诺在我的控制器中执行成功块。

HTML

<div ng-app="myApp">
    <div ng-controller="MainController">
         <h1>{{data}}</h1>
    </div>
<div>

JS

angular.module('services', []).service('myService', function($http) {
   this.getData = function() {
    return $http.get('test.json').then(function (response) {
        console.log(response);
        return response.data;
      },function(data) {
       console.log("Error block of service");
      });
   }
});


var app = angular.module('myApp', ['services']);

app.controller('MainController', ['$scope', 'myService', function ($scope, myService) {
    // Call the getData and set the response "data" in your scope.  
    myService.getData().then(function(myReponseData) {
        console.log("Success block of controller");
        $scope.data = myReponseData;
    },function(data) {
        console.log("Error block of controller");
        $scope.data = "Error " + data;
    });
}]);

我在 fiddle 中重现了同样的问题。看看JSFiddle

因为 Promise 就是这样设计的。

如果你 return catch 块内的任何东西,无论你 return 成为链中下一个 link 的 success

仅有的两种方法是:

  1. 在你的 catch 中重新抛出一个错误
  2. Return 一个被拒绝的 Promise inside your catch

这是一个更简单的例子:

Promise.reject(5)
  .catch(x => x * 2)
  .catch(err => console.log("THIS NEVER FIRES"))
  .then(x => console.log("Value is: ", x));
  // => "Value is: 10"

Promise.reject(5)
  .catch(x => Promise.reject(x * 2))
  .then(x => console.log("THIS NEVER FIRES"))
  .catch(err => console.log("Error is:", err));
  // => "Error is: 10"

在拒绝处理程序中,重新抛出错误很重要。否则被拒绝的承诺将转换为成功的承诺:

angular.module('services', []).service('myService', function($http) {
   this.getData = function() {
    return $http.get('test.json').then(function (response) {
        console.log(response);
        return response.data;
      },function(errorResponse) {
        console.log("Error block of service");
        //IMPORTANT re-throw error 
        throw errorResponse;
      });
   }
});

有关详细信息,请参阅 You're Missing the Point of Promises