How to handle one 404 in AngularJS $ q

I have a couple of chained $ http combined with one $ http using $ q.all ([prmiseA, promB]). Everything works fine, I return data and errors are processed without problems.

Unless data is found on a particular HTTP call, and this is not an error.

I use the service for the logic branch from the user interface. And my call looks like this.

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

What I would like to do is handle 404 on a single url inside the "Service.Call" function. So the user interface code above remains untouched.

My problem is that if I add an error handler to a specific call that can return 404. Then all errors are "handled" and therefore I lose errors for this call.

" " $q?

+4
1

" " $q?

, , :

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

$http 404 , . promises , :

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);
    }); 
}
+5

Source: https://habr.com/ru/post/1547632/


All Articles