我正在尝试捕获角度资源的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(function(result)(...)
中的代码已执行,我无法检测到响应HTTP状态代码。
所以,我的问题:
答案 0 :(得分:2)
第一个.catch
转换拒绝已完成。为防止转换,.catch
方法需要throw
错误。
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
服务会创建一个派生的承诺,该承诺会解析为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 语句。
答案 1 :(得分:1)
有一个函数可以捕获Angular中HTTP状态的响应。你可以在stack overflow http response
看看它是如何完成的答案 2 :(得分:0)
您可以使用拦截器。
在将请求传递给服务器和响应之前拦截请求 在将它们移交给启动的应用程序代码之前 这些要求
所以, 这将捕获源自$ http的所有响应错误,即$ resource。
$httpProvider.interceptors.push(function($q) {
return {
'responseError': function(response) {
if (response.status == 400) {
// Handle 400 error code
}
if (response.status == 503) {
// Handle 503 error code
}
// Rejects the derived promise.
return $q.reject(response);
}
};
});