go - 如何检查错误类型?

标签 go

我想检查我调用的函数的错误类型,看它是否是由 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.Errorinterface { Timeout() bool } 将作为一种类型工作。

关于go - 如何检查错误类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43947072/

相关文章:

go - 如何在gorethink中使用r.Do和r.Branch?

go - 如何使用http Response method Read in go?

go - 每个 tcp 连接上的每个 http 请求

dictionary - 使用 go lang 中的 map 实现更高阶的 fizz buzz?

google-app-engine - 如何在 Go 中的 AppEngine 数据存储区中建立多对多关系模型?

go - 如何将一片 Uint64 变成一片字节

go - 在 Go 中处理依赖关系

go - 如何在 Go 结构中设置默认值

html - 为什么在我输入电子邮件时没有显示我的订单状态?

html - golang 中是否有 boilerpipe?