英文:
How do I check the type of an error?
问题
我想检查我调用的函数中的错误类型,以查看是否是由deadlineExceededError引起的,但我没有找到引用它的方法。我想我可以始终根据.Error()
字符串进行检查,但我被告知这样做是不被赞同的。
另外,为了调试目的,它被设置为2微秒,我意识到应该将其更改为time.Minute
。
有关所讨论函数的Godoc文档:https://godoc.org/github.com/moby/moby/client#Client.ContainerStart
//如果容器在2分钟后启动失败,则应超时
ctx, cancel := context.WithTimeout(ctx, 2*time.Microsecond)
defer cancel()
// 进行实际的启动
if err := myClient.ContainerStart(ctx, containerName, types.ContainerStartOptions{}); err != nil {
fmt.Printf("%v\n", err) //打印:'context deadline exceeded'
fmt.Printf("%T\n", err) //打印:'context.deadlineExceededError'
switch e := err.(type) {
case //如何检查deadlineExceededError:
//在此处打印超时信息
}
return err
}
英文:
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
<!-- language: go -->
//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
}
答案1
得分: 4
你可以比较err == context.DeadlineExceeded
。
然而,正如Dave Cheney所提出的,你应该使用一个接口。
具体来说,net.Error
或interface { Timeout() bool }
将作为一种类型起作用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论