2014-07-11 116 views
2

,如果你有以下幾種方法:異常處理httpclient.GetStringAsync(URL)異步API調用

public async Task<string> GetTAsync(url) 
{ 
    return await httpClient.GetStringAsync(url); 
} 

public async Task<List<string>> Get(){ 
    var task1 = GetTAsync(url1); 
    var task2 = GetTAsync(url2); 
    await Task.WhenAll(new Task[]{task1, task2}); 
    // but this may through if any of the tasks fail. 
    //process both result 
} 

我如何處理異常?我查看了HttpClient.GetStringAsync(url)方法的文檔,它可能拋出的唯一異常似乎是ArgumentNullException。但至少我遇到了一次禁止的錯誤,並希望處理所有可能的例外情況。但我找不到任何特定的例外。我應該在這裏捕捉Exception exception嗎?如果它更具體,我將不勝感激。 請幫忙,它真的很重要。

+0

Catch'Exception',然後檢查它是否屬於'AggregateException'類型。如果是這樣,'AggregateException.InnerExceptions'使您可以訪問單個任務可能拋出的異常。注意'AggregateException'可以嵌套,你可以使用'AggregateException.Flatten'來解決這個問題。或者,在等待Task.WhenAll後,您可以訪問task.Result或在任務上執行await task,它將重新拋出該任務的異常。相關:http://stackoverflow.com/q/24623120/1768303。 – Noseratio

+0

是的,我可以捕捉聚合異常,並可以扁平化,但我想要的是特定的異常httpclient.GetStringAsync()方法可能會拋出。在查看其他帖子時,有人寫道HttpRequestException是將拋出的異常。到目前爲止,我無法確認它。 – user3818435

+0

你爲什麼不試試自己?你會得到'System.Net.Http.HttpRequestException'和相關的錯誤信息,例如「響應狀態碼不表示成功:404(未找到)。」請記住,類似於'404'的狀態會爲'HttpClient.GetStringAsync'引發錯誤,但不會引發'HttpClient.GetAsync'錯誤。 – Noseratio

回答

1

最後我想通如下:

public async Task<List<string>> Get() 
{ 
    var task1 = GetTAsync(url1); 
    var task2 = GetTAsync(url2); 
    var tasks = new List<Task>{task1, task2}; 
    //instead of calling Task.WhenAll and wait until all of them finishes 
    //and which messes me up when one of them throws, i got the following code 
    //to process each as they complete and handle their exception (if they throw too) 
    foreach(var task in tasks) 
    { 
     try{ 
     var result = await task; //this may throw so wrapping it in try catch block 
     //use result here 
     } 
     catch(Exception e) // I would appreciate if i get more specific exception but, 
         // even HttpRequestException as some indicates couldn't seem 
         // working so i am using more generic exception instead. 
     { 
     //deal with it 
     } 
    } 
} 

這是一個更好的解決辦法,我終於想通。如果有更好的東西,我很樂意聽到它。 我發佈這個 - 正義案件有人遇到同樣的問題。

+0

當你說'HttpRequestException'不工作時,你是什麼意思?你觀察到了什麼其他異常?我唯一記得的另一個例外是'TaskCanceledException'(這是HttpClient中的一個錯誤,請參閱https://social.msdn.microsoft.com/Forums/en-US/d8d87789-0ac9-4294-84a0 -91c9fa27e353 /臭蟲在-httpclientgetasync-應該拋出,引發WebException - 不taskcanceledexception?論壇= netfxnetcom)。該線程還暗示'WebException'是一種可能性,所以我想它也不會因爲檢查而產生傷害。 –

+0

這對我有意義。 [GetAsync]上的[MSDN文檔](https://msdn.microsoft.com/en-us/library/hh158944(v = vs.118).aspx)未指出'await GetAsync'可能會引發連接錯誤。所以,感謝你解決這個問題和解決方案,非常有幫助。 –