对promise的角度错误处理

时间:2014-01-21 18:51:14

标签: angularjs exception-handling promise

我是Angular的新手和承诺的一般想法所以请在这一点上承担。

我有以下承诺的一般设置:

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

我写这篇文章时认为function(error)会捕获getDataUriForUrl()调用中抛出的异常,但现在让我相信它是为了处理then(...区域中的错误。

我应该如何格式化这个以拦截我想要的错误? (捕获getDataUriForUrl()调用中抛出的异常)。

2 个答案:

答案 0 :(得分: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
});

答案 1 :(得分:0)

不是为每个api方法调用$ q.reject或$ q.resolve,而是可以为响应和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));

//注册拦截器

(function (global) {
    "use strict";

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

    }]);

}(this));

您可以参考Error Handling in angular了解更多信息。