douchilian1009 2019-05-11 01:04
浏览 32

如何检查错误是否为“超过最后期限”错误?

I'm sending a request with a context which specified with a 10 seconds timeout:

ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10)
defer cancel()
_, err := client.SendRequest(ctx)
if err != nil {
    return 0, err
}

now when I hit that timeout the error message is confusing:

context deadline exceeded

Is it possible to check if the err is the timeout error so that I can print a nicer error message?

ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10)
defer cancel()
_, err := client.SendRequest(ctx)
if err != nil {
    if isTimeoutError(err) {
       return nil, fmt.Errorf("the request is timeout after 10 seconds") 
    }
    return nil, err
}

How to implement such isTimeoutError function?

  • 写回答

1条回答 默认 最新

  • douluan5444 2019-05-11 01:13
    关注

    You can determine if an error is the result of a context timeout by comparing the error to context.DeadlineExceeded:

     if err == context.DeadlineExceeded {
         // context deadline exceeded
     }
    

    You can determine if an error is any timeout error using the following function:

    func isTimeoutError(err error) bool {
         e, ok := err.(net.Error)
         return ok && e.Timeout()
    }
    

    This function returns true all timeout errors including the value context.DeadlineExceeded. That value satisfies the net.Error interface and has a Timeout method that always returns true.

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大