加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:31:52 所属栏目:安全 来源:网络整理
导读:到目前为止,我已经使用Restangular对我的API进行了大约4次调用,并且在每一次调用中,我一直在检查它们的第二个参数,如下所示: Restangular.all("accounts").getList().then(function() { console.log("All ok");},function(response) { console.log("Error w
到目前为止,我已经使用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();

优点:

>不需要黑客:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读