未捕获错误状态代码

Error status codes are not being caught

我正在尝试捕获 angular 资源的 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 状态代码。

所以,我的问题:

  1. 为什么我的错误处理函数没有被执行?
  2. 如何检测 HTTP 响应状态代码?

Angular中有捕获HTTP状态响应的功能。您可以在此处查看它是如何完成的

第一个 .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;
    });

当函数省略 returnthrow 语句时,它会 returns 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',

要寻找的另一件事是应用程序中的其他 $http interceptors converting 通过省略 throw 语句的响应。

你可以使用拦截器。

Intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests

所以, 这将捕获所有来自 $http which $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);
        }
      };
    });