Catch exceptions while making web api calls

.net, api, asp.net, c#, http

Solution

if you are calling asp.net web api i would suggest you to use HttpClient which is done for that purposes

 try    
  {
     HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // Above three lines can be replaced with new helper method below 
     // string responseBody = await client.GetStringAsync(uri);

     Console.WriteLine(responseBody);
  }  
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");  
     Console.WriteLine("Message :{0} ",e.Message);
  }

This is example from MSDN how to deal with exceptions using http client

in you example you have

using (var client = new HttpClient())
      client.BaseAddress = new Uri(CairoBaseUrl);
      var getStringTask = client.GetStringAsync(requestUrl);
      response = await getStringTask;

But it wont work since await operator can be used only with methods marked async so it should be

  var getStringTask = await client.GetStringAsync(requestUrl);

Problem

I am making a lot of web api calls in my c# code. I don't know how to catch errors. Suppose, internet connection isn't working, then my code shows runtime error. How to I properly put them into try catch block, What's the general rule. All the articles I found were on how to throw back the error and error message. example API calls: ``` WebResponse webResponse = webRequest.GetResponse(); string res = webResponse.ToString(); ``` Also ``` using (var client = new HttpClient()) client.BaseAddress = new Uri(CairoBaseUrl); var getStringTask = client.GetStringAsync(requestUrl); response = await getStringTask; ``` And, ``` HttpResponseMessage response = await client.PostAsync( url,requestContent); ```

Original source