Angularjs Restangular的常规错误处理程序
到目前为止,我使用Restangular对我的API进行了大约4次调用,在每一次调用中,我都在then的第二个参数上检查它们,如下所示:Angularjs Restangular的常规错误处理程序,angularjs,restangular,Angularjs,Restangular,到目前为止,我使用Restangular对我的API进行了大约4次调用,在每一次调用中,我都在then的第二个参数上检查它们,如下所示: Restangular.all("accounts").getList().then(function() { console.log("All ok"); }, function(response) { console.log("Error with status code", response.status); }); 正如您所见,这不是一种
Restangular.all("accounts").getList().then(function() {
console.log("All ok");
}, function(response) {
console.log("Error with status code", response.status);
});
正如您所见,这不是一种可维护的方法,因为这会在整个应用程序中创建大量重复的错误处理代码
我理解存在,但是我无法想象它用于创建一般错误处理程序
我希望一些新的想法能在这个问题上帮助我
谢谢:)我也有类似的问题。errorInterceptor的问题是,它在任何回调之前被调用,所以我们可以选择总是做一些事情,而不仅仅是在我们需要它的时候。我用黑客的方式解决了这个问题,所以是否在代码中使用它取决于您自己。适用于:
"angular": "1.3.0",
"restangular": "1.4.0",
首先,我使用errorInterceptor:
RestangularConfigurer.setErrorInterceptor(function (response, deferred, responseHandler) {
var hasSomeErrback = deferred.promise.$$state.pending.map(function (thenAttachment) {
if (thenAttachment[2]) {
return true
}
else {
return false
}
}).reduce(function (accumulator, value) {
return accumulator || value
}, false)
if (!hasSomeErrback) {
myErrorService.globalError()
}
})
但我不是每次都调用全局错误处理程序(myErrorService.globalError()),而是在没有注册错误回调时才这样做。这是一个非常粗糙的方法,因为它使用promise对象的内部数据,但似乎有效,请参见测试:
describe('when server responded with error', function () {
beforeEach(function () {
spyOn(myErrorService, 'globalError')
$httpBackend.whenGET('/api/evil').respond(500, 'pure evil')
})
it('should call global error handler if error callback was NOT attached', function () {
myApiClient.all('evil').getList().then(function () {
})
$httpBackend.flush()
expect(myErrorService.globalError).toHaveBeenCalled()
})
it('shouldnt call global error handler if error callback was attached', function () {
myApiClient.all('evil').getList().then(function () {
}, function () {
console.log('Inside local catch')
})
$httpBackend.flush()
expect(myErrorService.globalError).not.toHaveBeenCalled()
})
it('shouldnt call global error handler if error callback was attached using catch', function () {
myApiClient.all('evil').getList().catch(function () {
})
$httpBackend.flush()
expect(myErrorService.globalError).not.toHaveBeenCalled()
})
})
我没有检查承诺链中是否有特定的错误处理程序,而是在承诺链的后面添加了可取消的常规错误处理程序:
Restangular.setErrorInterceptor(
function(response, deferred, responseHandler) {
var generalHandlerTimer = $timeout(function(){
generalErrorHanding(response);
},1);
response.cancelGeneralHandler = function(){
$timeout.cancel(generalHandlerTimer);
};
return true; // continue the promise chain
}
);
以及可能发生错误的调用:
restangularizedUser.patch({
user: {
email:newValue
}
}).then(function(res) {
//Success
}, function(response) {
//Error
//Cancel the general error handler due to I want to handle it on my way
response.cancelGeneralHandler();
$log.debug('Handle the ERROR on my specific way');
});
缺点:
- 如果需要使用特定的错误处理程序,则需要调用
响应.cancelGeneralHandler()代码>
- 不需要黑客:)