如何在AngularJS的$q中处理单个404

前端之家收集整理的这篇文章主要介绍了如何在AngularJS的$q中处理单个404前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有几个链接$http和一个$http使用$q.all([prmiseA,promiseB]).一切都工作正常,我得到了数据,错误处理没有问题.

除非有时在特定的http调用中找不到数据并且这不是错误.

我正在使用服务将逻辑与UI分开.我的电话看起来像这样

$scope.Loading = true;
var p = Service.Call(Param1,Param2);
p.then(function () {
    $scope.Loading = false;
},function (reason) { 
    $scope.Loading = false;
    $scope.alerts.push({ msg: "Error loading information " + Param1,type: "danger" });
})

我希望能够做的是在’Service.Call’函数中处理那个URL上的404.因此上面的UI代码保持不变.

我的问题是,如果我向可能返回404的特定调用添加错误处理程序.然后所有错误都被“处理”,因此我为这一个调用丢失了错误.

有没有办法在$q中“重新加注”?

@H_502_24@解决方法

Is there a way to “reraise” in $q?

是的,您可以通过从处理程序返回被拒绝的承诺来重新抛出:

return $q.reject(new Error("Re Thrown")); // this is an actual `throw` in most
                                          // promise implemenentations

如果$http调用404不是错误,您可以从中恢复.承诺的一个很酷的功能是我们可以从错误中恢复:

var makeCallAndRecover(url){
    return $http.get(...).catch(function(err){
        // recover here if err is 404
        if(err.status === 404) return null; //returning recovery
        // otherwise return a $q.reject
        return $q.reject(err);
    }); 
}

猜你在找的Angularjs相关文章