Exception handling for httpclient.GetStringAsync(url) async api call

10,434

Finally i figured it as follows:

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

This is a much better solution i finally figured. If there is something better, i would love to hear about it. I'm posting this -just case someone else runs into the same issue.

Share:
10,434
user3818435
Author by

user3818435

Updated on June 04, 2022

Comments

  • user3818435
    user3818435 almost 2 years

    if you have the following methods:

    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
    }
    

    How can I handle exception? I looked at the documentation for HttpClient.GetStringAsync(url) method and the only exception it might throw seems to be ArgumentNullException. But at least I run into forbidden error once and would like to handle all possible exception. But i can't find any specific exceptions. Should I catch just Exception exception here? I would appreciate if it is more specific. Please help, its really important.

  • Ohad Schneider
    Ohad Schneider almost 9 years
    What do you mean when you say HttpRequestException is not working? what other exception are you observing? The only other exception I got from it that I can recall was TaskCanceledException (which is a bug in HttpClient, see social.msdn.microsoft.com/Forums/en-US/…). That thread also implies WebException is a possibility so I guess it can't hurt to check for that too.
  • JJ Stiff
    JJ Stiff over 7 years
    This makes sense to me. The MSDN doc on GetAsync not indicate that await GetAsync might throw a connection error. So thank you for this problem and solution, very helpful.