AngularJS HTTP请求错误处理

时间:2017-11-25 17:35:52

标签: angularjs angularjs-http

我已经看到了Restful API facotires错误处理的不同示例,这有点令人困惑。这是两个例子:

A

angular.module('app').controller('userCtrl', function($scope, User) {
    $scope.users = [];
    $scope.error = '';

    User.getUsers().then(function(response) {
        $scope.users = response.data;
    }, function(response) {
        $scope.error = 'Users not found';
    })
});

angular.module('app').factory('User', function($http) {
    var service = {};

    service.getUsers = function() {
        return $http.get('url-here').then(function(response) {
            return response;
        });
    }

    return service;
});

angular.module('app').controller('userCtrl', function($scope, User) {
    $scope.users = [];
    $scope.error = '';

    User.getUsers().then(function(response) {
        if(response.status == 404) {
            $scope.error = 'Users not found';
        } else {
            $scope.users = response.data;
        }
    });
});

angular.module('app').factory('User', function($http) {
    var service = {};

    service.getUsers = function() {
        return $http.get('url-here', function(response) {
            return response;
        }, function(response) {
            return response;
        });
    }

    return service;
});

哪一个是最佳做法?就像,如果没有找到用户,我会的 想告诉没有用户,如果有内部服务器错误(500),我想说出类似的事情"出了点问题,稍后再试一次"。

1 个答案:

答案 0 :(得分:0)

我会选择 A ,原因有两个:

  • 显然发生了错误。
  • 您可以根据它们出现的页面对这些错误进行个性化处理(根据用户所在的页面或组件,您可能会有不同的错误处理404错误)。

然后,您可以使用switch语句根据错误代码提供特定邮件,如下所示:

User.getUsers().then(function(response) {

    $scope.users = response.data;

}, function(response) { // error has occured

    switch(response.status) {

        case "404":
            $scope.error = "Users not found.";
            break;

        case "403":
            $scope.error = "You do not have permission to view these users.";
            break;

        case "500":
            $scope.error = "We are having server issues. Please try again in 10 minutes.";
            break;
    }
});