angularjs $ resource的默认(通用)错误处理

时间:2014-08-21 07:53:45

标签: javascript angularjs error-handling promise ngresource

我想为angularjs资源的所有方法实现一个通用错误回调,它会记录“Default Error Handler Log”。

我的资源:

currentNgModule.factory('StatusesResource', function($resource, $timeout){
    var StatusesResource = $resource(get_gui_url_param('company.employee.statuses', true), null, {
            get: {method: 'GET', isArray: true, headers: getGenericHttpHeaders()},
            create: {method: 'POST', isArray: false, headers: getGenericHttpHeaders()},
            $update: {
                method: 'PATCH',
                isArray: false,
                headers: getGenericHttpHeaders(),
                url: get_gui_url_param('company.employee.status.pk', true)
            },
            delete: {
                method: 'DELETE',
                isArray: false,
                headers: getGenericHttpHeaders(),
                url: get_gui_url_param('company.employee.status.pk', true)
            }
        }, false);

    return StatusesResource;
});

例如,执行结果:

$log.debug("Calling Resource Get")
StatusesResource.get({employee_pk: pk},
    function(){$log.debug("success")},
    function(){$log.debug("Get error")}
);

$log.debug("Calling Resource Delete")
StatusesResource.get({pk: pk},
    function(){$log.debug("success")},
    function(){$log.debug("Delete error")}
);

我想获得以下日志:

Calling Resource Get
Default Error Handler Log
Get error
Calling Resource Delete
Default Error Handler Log
Delete error

热门为ng-resource实现此默认(初始,通用)回调(成功,错误)?

1 个答案:

答案 0 :(得分:0)

您可以执行此操作using the interceptor property of the resource action definition。有关详情,请参阅the $resource docs

所以:

function resourceResponseErrorHandler(response) {
  $log.error("Resource error");
}

currentNgModule.factory('StatusesResource', function($resource, $timeout){
    var StatusesResource = $resource(get_gui_url_param('company.employee.statuses', true), null, {
            get: {method: 'GET', isArray: true, headers: getGenericHttpHeaders(), interceptor: { resonseError: resourceResponseErrorHandler }},
            create: {method: 'POST', isArray: false, headers: getGenericHttpHeaders(), interceptor: { resonseError: resourceResponseErrorHandler }},
            $update: {
                method: 'PATCH',
                isArray: false,
                headers: getGenericHttpHeaders(),
                url: get_gui_url_param('company.employee.status.pk', true),
                interceptor: { resonseError: resourceResponseErrorHandler }
            },
            delete: {
                method: 'DELETE',
                isArray: false,
                headers: getGenericHttpHeaders(),
                url: get_gui_url_param('company.employee.status.pk', true),
                interceptor: { resonseError: resourceResponseErrorHandler }
            }
        }, false);

    return StatusesResource;
});