问美元。reject不会在$http.get()中重新抛出异常。

时间:2021-03-08 19:41:42

I'm dealing with code like this:

我处理的代码是这样的:

return promise.then(function(url) {
    return $http.get(url, data);
}).then(function (response) {
    return response.data;
}).catch(function (response) {
    return $q.reject(response);
});

All I want to do is to reject the promise in the "catch" block so the exception is logged by my custom implementation of $exceptionHandler.

我所要做的就是在“catch”块中拒绝这个承诺,所以这个异常是由我的$exceptionHandler的自定义实现记录的。

According to my understanding of the documentation, the line below is supposed to rethrow the exception but it is not doing it. Thus, $exceptionHandler never handlers the exception:

根据我对文档的理解,下面的一行应该重新抛出异常,但它没有这么做。因此,$exceptionHandler从不处理异常:

return $q.reject(reason); // why isn't it rethrowing?

Chances are I'm misunderstanding the documentation.

我可能误解了文件。

1 个解决方案

#1


2  

The error is re throwing - as controller can catch error and displays it.

错误是重新抛出——因为控制器可以捕获错误并显示它。

angular.module('app', [])
  .controller('app', function($scope, service) {
    $scope.error = {}
    service
      .load('foo')
      .catch(function(error) {
        angular.extend($scope.error, {
          reason: error
        });
      });
  })
  .service('service', function($http, $q) {

    var promise = function promise() {
      var d = $q.defer();
      d.reject('some reason')
      return d.promise;
    }();

    this.load = function(url) {
      return promise
        .then(function() {
          return $http.get(url);
        })
        .then(function(response) {
          return response.data;
        })
        .catch(function(reason) {
          return $q.reject(reason);
        });
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app'>
  <div ng-controller='app'>error: {{ error.reason }}</div>
</div>

#1


2  

The error is re throwing - as controller can catch error and displays it.

错误是重新抛出——因为控制器可以捕获错误并显示它。

angular.module('app', [])
  .controller('app', function($scope, service) {
    $scope.error = {}
    service
      .load('foo')
      .catch(function(error) {
        angular.extend($scope.error, {
          reason: error
        });
      });
  })
  .service('service', function($http, $q) {

    var promise = function promise() {
      var d = $q.defer();
      d.reject('some reason')
      return d.promise;
    }();

    this.load = function(url) {
      return promise
        .then(function() {
          return $http.get(url);
        })
        .then(function(response) {
          return response.data;
        })
        .catch(function(reason) {
          return $q.reject(reason);
        });
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app'>
  <div ng-controller='app'>error: {{ error.reason }}</div>
</div>