我想检查我调用的函数的错误类型,看它是否是由 deadlineExceededError 引起的,但我没有找到引用它的方法。我想我总是可以检查 .Error()
字符串,但我被告知这是不受欢迎的。
为了调试目的,它也设置为 2 微秒,我意识到它应该更改为 time.Minute
有关函数的 Godoc: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\n", err) //prints: 'context deadline exceeded'
fmt.Printf("%T\n", err) //prints: 'context.deadlineExceededError'
switch e := err.(type) {
case //how do I check for deadlineExceededError:
//print that it timed out here
}
return err
}
最佳答案
context package exposes this value as a variable .
可以比较err == context.DeadlineExceeded
。
然而,作为argued by Dave Cheney ,您可能应该改用接口(interface)。
特别是net.Error
或 interface { Timeout() bool }
将作为一种类型工作。
关于go - 如何检查错误类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43947072/