Daniel
Daniel

Reputation: 11

How to catch/handle WebException and SocketException with HttpClient

My problem is: for example if target server is offline, not available

When calling any HttpClient async methods such PostAsync, GetAsync, SendAsync; it will NOT throw any exception but execution will jump out the executing method. Visual Studio (when I am debugging) will be the one will throw exceptions

WebException: Unable to connect to the remote server SocketException: No connection could be made because the target machine actively refuse it...

Question: How to handle such scenario with HttpClient? Catch that WebException and SocketException?

Below are sample code:

async void DoApiFoo()
{
  try
  {
     var r = new HttpRequestMessage(HttpMethod.Post, url);
     r.Content = content;
     // if server if offline, execution will step over DoApiFoo and go back to CallFoo 
     var response = await httpClient.SendAsync(r, HttpCompletionOption.ResponseHeadersRead);

      // this line will not hit
      response.EnsureSuccessStatusCode();
   }
   catch (Exception)
    {
      // no exception thrown
       throw;
    }

}

async void CallFoo()
{
  var result = await DoApiFoo();
  
}

Upvotes: 0

Views: 518

Answers (1)

ThomasArdal
ThomasArdal

Reputation: 5229

Your catch block will catch any exceptions in both the SendAsync method and during the call to EnsireSuccessStatusCode. Since you have a throw statement in the catch block, Visual Studio will show the outer call that triggers the exception. If you run the code with a debugger and set a breakpoint on the throw line you will see that the debugger successfully breaks on this line.

I assume that the code you have included in the question is something written for the question only. It is missing variables and generally doesn't compile.

Upvotes: 1

Related Questions