2014-01-21 163 views
0

我是新来的角和承诺的一般想法,所以请与我在这一个承担。对承诺的角度错误处理

我有如下承诺这个一般设置:

ApiService.getDataUriForUrl(imageUrl).then(function(url){ 
    requests--; 
}, function(error){ 
    console.log('oh no!'); 
}); 

我写了这个想法了function(error)会赶上扔到getDataUriForUrl()通话异常,但我现在带领相信这是处理错误在then(...区域。

我应该如何格式化它来拦截错误? (捕获getDataUriForUrl()调用中引发的异常)。

+2

你的语法是正确的,但要清楚它不会赶上getDataUriForUrl例外,它反而抓住故障。这意味着你必须显式调用getDataUriForUrl中的$ q.reject。 因此,请考虑作为.resolve和.reject处理程序的promise和success中的成功和失败。服务或API的创建者必须调用这些函数。 编辑:一个简单的解决将是赶服务中的错误和简单的调用$ q.reject –

+0

好吧,非常感谢你,帮我解决这个问题。 – Hoser

回答

3

在onFulfill回调抛出的错误将不会被传递到onReject回调。 相反,您可以将第一个回调传递给then方法,然后在返回时调用then方法老化。

ApiService.getDataUriForUrl(imageUrl).then(function(url){ 
    requests--; 
    return new Error();// you can't throw it 
}).then(null, function(error){ 
    console.log('oh no!');// I can catch error from the getData or the onFulfill callback 
}); 
0

而不是为每个api方法调用$ q.reject或$ q.resolve,你可以为response和responseError编写一个拦截器。你可以在其中只有$ q.reject()或$ q.resolve()。 这将更清洁和模块化。

示例代码:

(function (global) { 
    "use strict"; 

    angular.module("TestAPp").factory('httpInterceptor', ["$rootScope", "$q", function ($rootScope, $q) { 
     return { 
      response:function(response){ 
       return response; 
      }, 
      responseError: function (response) { 
       return $q.reject(response); 
      } 
     }; 
    }]); 

}(this)); 

//注册interceprtor

(function (global) { 
    "use strict"; 

    angular.module("TestApp", []) 
      .config([ '$httpProvider',function ($httpProvider) { 
       /* Register the interceptor */ 
       $httpProvider.interceptors.push('httpInterceptor'); 

    }]); 

}(this)); 

您可以参考Error Handling in angular获取更多信息。