2014-07-11 117 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'可能会引发连接错误。所以,感谢你解决这个问题和解决方案,非常有帮助。 –