如何在$ http承诺中抛出错误

问题描述 投票:4回答:4

我有一个角度服务,包装我的其余api调用并返回$ http承诺。

我的问题是如何抛出一个错误,以便调用触发.error方法的promise?我不想抛出错误,因为我希望它在调用函数中使用.success / .error而不是在它周围执行try catch块。

myFunction: function(foo)
   if (foo) {
      return $http.put(rootUrl + '/bar', {foo: foo});
   }
   else {
      //what do I return here to trigger the .error promise in the calling function
   }
angularjs angular-promise
4个回答
0
投票

首先在您的服务中注入$ q-service。然后在你的其他地方:

else {
     var deferred = $q.defer();
     deferred.reject("reject reason, foo was false");
     return deferred.promise;
}

不像Blazemonger那样聪明,但它很快就能做到。


6
投票

你不需要$q.defer()。还有else。您可以直接使用拒绝:

myFunction: function(foo) {
    if (foo) {
        return $http.put(rootUrl + '/bar', {foo: foo});
    }

    return $q.reject("reject reason");
}

请参阅https://docs.angularjs.org/api/ng/service/ $ q#reject


1
投票

你会想要create your own promise using $q。以下是我在最近的一个项目中做了类似的事情:

app.service('allData', ['$http','$q',function($http,$q) {
    return {
        getJson: function() {
            return $q(function(resolve, reject) { // return a promise
                $http.get('/path/to/data.json', {cache:true})
                    .success(function(data) {
                        if (angular.isArray(data)) { // should be an ordered array
                        // or any other test you like that proves it's valid
                            resolve(data);
                        } else {
                            reject("Invalid JSON returned");
                            console.log(data);
                        };
                    })
                    .error(function(data) {
                        reject("Invalid data returned");
                        console.log(data);
                    });
            });
        }
    };
}]);

在我的控制器中:

allData.getJson().then(function(json) {
    // success, do something with the json
}, function(reason) { // failure, .getJson() had some kind of error
    alert('Sorry, unable to retrieve data from the server.')
    console.error(reason);
});

0
投票

您可以使用throw new Error ("custom error")引发或抛出自定义错误。

对于http:

http.get('url').toPromise().then (result =>{
  throw new Error ("My Custom Error") // New Custom error  New is optional w
}).catch(err => {
  throw  err
}); // catch will catch any error occur while http call 
© www.soinside.com 2019 - 2024. All rights reserved.