我试图捕获角度资源的HTTP错误状态代码(!= 200).
我的服务,我有资源定义:
(apiService.js)
我的服务,我有资源定义:
(apiService.js)
.factory('ApiService',function($resource,$http,localStorageService,CONFIG) { var base_api_url = api_url = CONFIG.api_url,api_version_prefix = CONFIG.api_version_prefix; return { userDevices: $resource(api_url+'/requestRegistration/userDevices/:action',{},{ registerDevice: { method: 'POST',params: { action: '' } },verify: { method: 'POST',params: { action: 'verify' } },} } });
我的控制器代码:
.controller('LoginCtrl',function(CONFIG,$scope,$state,$ionicPlatform,$ionicPopup,ApiService) { $scope.data = { username: null }; $scope.registerDevice = function() { if($scope.data.username) { var authenticationResponse = ApiService.userDevices.registerDevice({ username: $scope.data.username }); authenticationResponse.$promise.then(function(result) { // this is always fired,even then response code is 400 or 503 :( I am not able to check response status code. console.log(result); console.log('success!'); },function(error){ // this code is not being exectued even when response status code is different then 200 // its never executed at all :( console.log('error!'); }); } }; });
当我发送请求并收到响应代码400/503时,我认为应该执行功能(错误)代码,但事实并非如此.
相反,我的$promise.then中的代码(函数(结果)(…)被执行,我无法检测响应HTTP状态代码.
所以,我的问题:
解决方法
第一个.catch将拒绝转换为已完成.为防止转换,.catch方法需要抛出错误.
authenticationResponse.$promise.catch(function(error){ alert('catched error!!!'); //throw to chain error throw error; }).then(function(result) { // this is always fired,even then response code is 400 or 503 :( console.log(result); console.log('success!'); //return to chain data return result },function(error){ // This should be executed when status code is different then 200? // its never executed at all :( console.log('error!'); //throw to chain rejection throw error; });
当函数省略return或throw语句时,它返回undefined. $q服务创建派生的promise,解析为undefined.
诊断ngResource问题
userDevices: $resource(api_url+'/requestRegistration/userDevices/:action',{ registerDevice: { method: 'POST',params: { action: '' },interceptor: { response: function (response) { console.log("registerDevice success"); console.log(response.status); return response; },errorResponse: function (errorResponse) { console.log("registerDevice error"); console.log(errorResponse.status); throw errorResponse; } } },verify: { method: 'POST',
要寻找的另一件事是App中的其他$http interceptors通过省略throw语句来转换响应.