angularjs – 未捕获错误状态代码
发布时间:2020-12-17 17:17:05 所属栏目:安全 来源:网络整理
导读:我试图捕获角度资源的HTTP错误状态代码(!= 200). 我的服务,我有资源定义: (apiService.js) .factory('ApiService',function($resource,$http,localStorageService,CONFIG) { var base_api_url = api_url = CONFIG.api_url,api_version_prefix = CONFIG.api
我试图捕获角度资源的HTTP错误状态代码(!= 200).
我的服务,我有资源定义: (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问题 要诊断$resource方法的问题,请添加响应拦截器: 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语句来转换响应. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |