angularjs – Restangular的常规错误处理程序

前端之家收集整理的这篇文章主要介绍了angularjs – Restangular的常规错误处理程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
到目前为止,我已经使用Restangular对我的API进行了大约4次调用,并且在每一次调用中,我一直在检查它们的第二个参数,如下所示:

Restangular.all("accounts").getList().then(function() {
   console.log("All ok");
},function(response) {
   console.log("Error with status code",response.status);
});

正如您所看到的,这不是一种可维护的方法,因为这会在整个应用程序中创建大量重复的错误处理代码.

我知道errorInterceptor存在然而我无法想象它用于创建一般错误处理程序.

我希望也许一些新想法可以帮助我解决这个问题.

谢谢 :)

解决方法

而不是检查我们是否在promise链中有一个特定的错误处理程序,我添加了我的一般错误处理程序,可以在promise链的后面取消:

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');
        });

坏处:

>如果需要使用特定的错误处理程序,则需要调用response.cancelGeneralHandler();

优点:

>不需要黑客:)

猜你在找的Angularjs相关文章