我在使用restangular从400错误标头获取响应时遇到问题。我写的代码是:
var loginData = Restangular.all("login");
$scope.postForm = function() {
loginData.post($scope.formData).then(function(response){
var error = response.error;
if(error) {
$scope.error = response.message;
} else {
localStorageService.clearAll();
localStorageService.set('xxx', response.id);
localStorageService.set('xxx', response.apiKey);
$location.path('/main');
}
});
}
当我返回200头时,$ scope.error获取response.message,但是当响应头为400时没有。我设置了setErrorInterceptor()以将消息记录到控制台但我无法弄清楚如何让它返回响应,以便我可以设置$ scope.header。
编辑:这是我在setErrorInterceptor()
中将消息记录到控制台的方式RestangularProvider.setErrorInterceptor(
function(response) {
if (response.status == 401) {
console.log("Login required... ");
$window.location.href='/login';
} else if (response.status == 400) {
console.log(response.data.message);
} else {
console.log("Response received with HTTP error code: " + response.status );
}
return false; // I also tried commenting return false out
});
答案 0 :(得分:3)
在常见问题解答中查看How can I handle errors。您需要将第二个函数传递给promise的then()
方法,以充当错误处理程序。
Restangular.all("accounts").getList().then(function() {
console.log("All ok");
}, function(response) {
console.log("Error with status code", response.status);
});