Angular Catch方法无法使用$ http get请求

时间:2017-03-10 17:35:41

标签: angularjs angular-promise angular-http

我正在尝试在处理来自API的错误时整齐地管理来自控制器的服务函数调用。

但是,当我执行以下操作时,即使API返回403或404,我仍然会在控制台中获得this is showing even with 403 and 404 errors

我假设如果我在我的服务文件中添加catch,这可能会有效,但我更希望从控制器中保持这个管理。这可能吗?

控制器:

angular.module('EnterDataCtrl', []).controller('EnterDataController', ['$scope', 'Data', '$state', function ($scope, Data, $state) {
    vm = this;
    vm.getRules = function (e, rule_query, data) {
        if (e.keyCode == 13) {

            Data.getRules(rule_query,data).then(function (data) {
                console.log('this is showing even with 403 and 404 errors');
            }).catch(function(res) {
                console.log(res);
            });
        }
    }
}]);

服务

angular.module('EnterDataService', []).factory('Data', ['$http', function ($http) {

    return {

        getRules: function getRules(rule_query,data) {
            var apiBase = apiUrl + 'get-rules';
            var config = {
                handleError:true,
                params: {
                    rule_query: rule_query,
                    data : data
                }
            };
            return $http.get(apiBase, config).catch(function () {});
        }

    }
}]);

2 个答案:

答案 0 :(得分:0)

在您的服务中,您正在设置捕获而不做任何事情。这通常是不好的做法,如果您要使用catch块,那么在那里处理错误。如果没有,请不要声明捕获。

您可以从服务方法中完全删除catch,这会导致控制器捕获它。

或者,您可以在服务调用中保留catch,并确保抛出以便错误正确地冒泡。

答案 1 :(得分:0)

当拒绝处理程序省略throw语句时,它返回undefined。此会将已拒绝的承诺转换为已解决为undefined的履行承诺。

为避免意外转换,在拒绝处理程序中包含throw语句非常重要。

app.service('Data', ['$http', function ($http) {

    this.getRules = function getRules(rule_query,data) {
        var apiBase = apiUrl + 'get-rules';
        var config = {
            handleError:true,
            params: {
                rule_query: rule_query,
                data : data
            }
        };
        //return $http.get(apiBase, config).catch(function () {});
        return $http.get(apiBase, config)
          .catch(function (errorResponse) {
             console.error("Data service error");
             //IMPORTANT
             throw errorResponse;
        });
    }
}]);