简体   繁体   中英

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();
  
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM