简体   繁体   English

如何使用 HttpClient 捕获/处理 WebException 和 SocketException

[英]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;调用任何 HttpClient 异步方法时,如 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 Visual Studio(当我调试时)会抛出异常

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

Question: How to handle such scenario with HttpClient?问题:如何使用 HttpClient 处理这种情况? Catch that WebException and SocketException?抓住那个 WebException 和 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 .您的catch块将在SendAsync方法和调用EnsireSuccessStatusCode期间捕获任何异常。 Since you have a throw statement in the catch block, Visual Studio will show the outer call that triggers the exception.由于在 catch 块中有一个throw语句,Visual Studio 将显示触发异常的外部调用。 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.如果您使用调试器运行代码并在throw行上设置断点,您将看到调试器成功地在该行中断。

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.它缺少变量,通常无法编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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