httpclient.GetStringAsync(url) async api调用的异常处理

本文关键字:api 调用 异常处理 async GetStringAsync url httpclient | 更新日期: 2023-09-27 18:12:37

如果您有以下方法:

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异常吗?如果能更具体一点,我会很感激。

httpclient.GetStringAsync(url) async api调用的异常处理

最后我想了一下:

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 
      }
   } 
}

这是一个更好的解决方案,我终于想到了。如果有更好的办法,我很乐意听听。我把这个贴出来,以防别人遇到同样的问题。