如何检查错误的类型?

huangapple go评论115阅读模式
英文:

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(&quot;%v\n&quot;, err) //prints: &#39;context deadline exceeded&#39;
	fmt.Printf(&quot;%T\n&quot;, err) //prints: &#39;context.deadlineExceededError&#39;
    switch e := err.(type) {
	case //how do I check for deadlineExceededError:
         //print that it timed out here
	}
	return err
}

答案1

得分: 4

context包将此值作为变量公开

你可以比较err == context.DeadlineExceeded

然而,正如Dave Cheney所提出的,你应该使用一个接口。

具体来说,net.Errorinterface { 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.

huangapple
  • 本文由 发表于 2017年5月13日 06:05:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/43947072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定