douyi1982 2017-05-12 22:05
浏览 26
已采纳

如何检查错误的类型?

I want to check the error type from a function I call to see if it was caused by a deadlineExceededError but I don't see a way to reference it. I suppose I can always check against the .Error() string but I've been told that's frowned upon.

Also it's set to 2 microseconds for debugging purposes, I realize it should be changed to time.Minute

Godoc for the function in question: https://godoc.org/github.com/moby/moby/client#Client.ContainerStart

//if the container fails to start after 2 minutes then we should timeout
ctx, cancel := context.WithTimeout(ctx, 2*time.Microsecond)

defer cancel()
// Do the actual start
if err := myClient.ContainerStart(ctx, containerName, types.ContainerStartOptions{}); err != nil {
    fmt.Printf("%v
", err) //prints: 'context deadline exceeded'
    fmt.Printf("%T
", err) //prints: 'context.deadlineExceededError'
    switch e := err.(type) {
    case //how do I check for deadlineExceededError:
         //print that it timed out here
    }
    return err
}
  • 写回答

1条回答 默认 最新

  • douxun3496 2017-05-12 22:11
    关注

    The context package exposes this value as a variable.

    You can compare err == context.DeadlineExceeded.

    However, as argued by Dave Cheney, you should probably use an interface instead.

    Specifically net.Error or interface { Timeout() bool } will work as a type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别