尝试为资源实现全局错误处理程序时,角度“响应未定义”

时间:2016-02-17 15:10:23

标签: javascript angularjs angularjs-resource

我是angular的新手,并试图创建一个全局错误处理程序。每当使用500 http状态调用资源时,我都想重定向到一般错误页面。

每当我实现一个注入器时,我都会收到“响应未定义”错误。我究竟做错了什么?我目前已将注释重定向并仍然收到错误。

var appServices = angular.module('appServices', ['ngResource']);

appServices.factory('ApplicationService', ['$resource', function ($resource) {
    return $resource('http://localhost:23357/api/application/:id', { id: '@id' }, {
        update: {
            method: 'PUT'
        }
    });
}]);

appServices.factory('globalErrorInterceptor', ['$location', '$q', '$injector', function ($location, $q, $injector) {
    return {
        'responseError': function (r) {
            console.log('global error test');

            /*
            commented out for testing
            if (r.status == 500) {
               $location.path('/error');
            }
            else
               return $q.reject(r);
            */

            return $q.reject(r);
        }
    }
}]);

appServices.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('globalErrorInterceptor')
}]);

然后在我的控制器中我这样调用资源。目前,Web服务设置为始终返回500。

$scope.applications = ApplicationService.query();

1 个答案:

答案 0 :(得分:0)

我需要始终返回$ q.reject,因此工作拦截器看起来像:

appServices.factory('globalErrorInterceptor', ['$location', '$q', '$injector', function ($location, $q, $injector) {
    return {
        'responseError': function (r) {
            console.log(r);

            if (r.status == 500) {
                $location.path('/error');
            }

            return $q.reject(r);
        }
    }
}]);
相关问题