在.NET中你们是如何捕捉 HttpClient中的超时错误的

2019-03-01 08:33发布

我在测试代码中写了这段代码,但是抛出的One or more errors occurred. (A task was canceled.)

System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()
 {
         BaseAddress = new Uri("https://www.taobao.com"),
         Timeout = TimeSpan.FromMilliseconds(10)
 };
 Assert.Throws<TimeoutException>(() =>
 {
          var s = client.GetAsync("").Result;
 });
Assert.Throws() Failure
Expected: typeof(System.TimeoutException)
Actual:   typeof(System.AggregateException): One or more errors occurred. (A task was canceled.)

大家在代码中都是如何捕获这个错误的呢?

Github上的讨论:
HttpClient throws TaskCanceledException on timeout
StackOverflow上的讨论:
How can I tell when HttpClient has timed out?

1条回答
Explosion°爆炸
2楼-- · 2019-03-01 09:07

HttpClient.Timeout 属性的帮助文档:

//
// Summary:
//     Gets or sets the timespan to wait before the request times out.
//
// Returns:
//     The timespan to wait before the request times out.
//
// Exceptions:
//   T:System.ArgumentOutOfRangeException:
//     The timeout specified is less than or equal to zero and is not System.Threading.Timeout.InfiniteTimeSpan.
//
//   T:System.InvalidOperationException:
//     An operation has already been started on the current instance.
//
//   T:System.ObjectDisposedException:
//     The current instance has been disposed.

Timeout 设置只是的是一个等待时间,Timeout = TimeSpan.FromMilliseconds(10) 只是表示等10秒,如果超过 10 秒就取消当前的 Task ,实际 TCP 层面没有发生超时。

在这样的情况下,对于 HttpClient 来说就是我等了10秒钟你没来,我走人,我根本不知道你为什么没来,你让 HttpClient 报什么更有用的异常?

查看更多
登录 后发表回答