2014-01-21 178 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獲取更多信息。