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.

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

报告相同问题?