【问题标题】:Exception handling for httpclient.GetStringAsync(url) async api callhttpclient.GetStringAsync(url) 异步 api 调用的异常处理
【发布时间】:2014-07-11 02:35:25
【问题描述】:

如果你有以下方法:

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,然后检查是否为AggregateException类型。如果是这样,AggregateException.InnerExceptions 使您可以访问可能由单个任务引发的异常。注意AggregateException 可以嵌套,您可以使用AggregateException.Flatten 来说明这一点。或者,在await Task.WhenAll 之后,您可以只访问task.Result 或对单个任务执行await task,它将重新抛出任务的异常。相关:stackoverflow.com/q/24623120/1768303.
  • 是的,我可以捕获聚合异常并将其展平,但我想要的是 httpclient.GetStringAsync() 方法可能抛出的特定异常。在查看其他帖子时,有人写道 HttpRequestException 是将抛出的异常。到目前为止,我无法确认。
  • 你自己试试看吧?您将收到带有相关错误信息的 System.Net.Http.HttpRequestException,例如“响应状态码不表示成功:404(未找到)。”请记住,像404 这样的状态会为HttpClient.GetStringAsync 抛出错误,但不会为HttpClient.GetAsync 抛出错误。
  • 我试过但没有得到 HttpRequestException 或 Aggregate 异常。但是我得到了 InvalidOperationException。我不知道这是否是您收到 404 或 403 错误时的预期结果。
  • 当我使用无效的 URL 调用 GetStringAsync 时,我得到了 HttpRequestException。如果没有看到调用GetStringAsync 的实际代码并且可以访问URL,很难说出为什么你会得到InvalidOperationException。使用 Fiddler 监视 HTTP 数据包。

标签: c# exception-handling async-await httpclient


【解决方案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 
      }
   } 
}

这是我最终想到的更好的解决方案。如果有更好的东西,我很想听听。 我正在发布这个 - 以防其他人遇到同样的问题。

【讨论】:

  • HttpRequestException 不起作用是什么意思?您还观察到什么其他异常?我记得的唯一其他例外是​​TaskCanceledException(这是HttpClient 中的一个错误,请参阅social.msdn.microsoft.com/Forums/en-US/…)。该线程还暗示WebException 是一种可能性,所以我想检查一下也无妨。
  • 这对我来说很有意义。 MSDN doc on GetAsync 不表示 await GetAsync 可能会引发连接错误。非常感谢您提供这个问题和解决方案,非常有帮助。
猜你喜欢
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多