首页 新闻 会员 周边 捐助

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

1
悬赏园豆:50 [已解决问题] 解决于 2019-03-01 09:21

我在测试代码中写了这段代码,但是抛出的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?

BUTTERAPPLE的主页 BUTTERAPPLE | 老鸟四级 | 园豆:3190
提问于:2019-02-28 12:48
< >
分享
最佳答案
5

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 报什么更有用的异常?

收获园豆:50
dudu | 高人七级 |园豆:29732 | 2019-02-28 14:14

如果你想捕捉到 tcp 层面的超时异常,需要把 HttpClient.Timeout 的值设置为大于等于 tcp 的超时时间

dudu | 园豆:29732 (高人七级) | 2019-02-28 14:19

@dudu: 确实没想到 tcp层面的超时,我去了解一下。[飞吻]

BUTTERAPPLE | 园豆:3190 (老鸟四级) | 2019-02-28 14:38

dudu 太强了!

Shendu.CC | 园豆:2138 (老鸟四级) | 2019-02-28 17:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册