我已经看到了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),我想说出类似的事情"出了点问题,稍后再试一次"。
答案 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;
}
});