![](/img/trans.png)
[英]How to catch 404 WebException for WebClient.DownloadFileAsync
[英]How to catch/handle WebException and SocketException with HttpClient
我的问题是:例如,如果目标服务器离线,不可用
调用任何 HttpClient 异步方法时,如 PostAsync、GetAsync、SendAsync; 它不会抛出任何异常,但执行会跳出执行方法。 Visual Studio(当我调试时)会抛出异常
WebException: Unable to connect to the remote server SocketException: No connection could be made because the target machine主动拒绝...
问题:如何使用 HttpClient 处理这种情况? 抓住那个 WebException 和 SocketException?
以下是示例代码:
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();
}
您的catch
块将在SendAsync
方法和调用EnsireSuccessStatusCode
期间捕获任何异常。 由于在 catch 块中有一个throw
语句,Visual Studio 将显示触发异常的外部调用。 如果您使用调试器运行代码并在throw
行上设置断点,您将看到调试器成功地在该行中断。
我假设您在问题中包含的代码仅是为该问题编写的。 它缺少变量,通常无法编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.