过滤掉损坏的管道错误

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

Filter out broken pipe errors

问题

我从一个io.Copy调用中得到一个error,我将一个套接字(TCPConn)作为目标传递给它。预期远程主机在不再需要时会简单地断开连接,而我没有收到任何来自它们的内容。

当断开连接发生时,我会得到以下错误:

write tcp 192.168.26.5:21277: broken pipe

但是我只有一个error接口。如何区分断开管道错误和其他类型的错误?

if err.Errno == EPIPE...
英文:

I'm getting an error returned from an io.Copy call, to which I've passed a socket (TCPConn) as the destination. It's expected that the remote host will simply drop the connection when they've had enough, and I'm not receiving anything from them.

When the drop occurs, I get this error:

write tcp 192.168.26.5:21277: broken pipe

But all I have is an error interface. How can I differentiate broken pipe errors from other kinds of error?

if err.Errno == EPIPE...

答案1

得分: 19

The broken pipe error is defined in the syscall package. You can use the equality operator to compare the error to the one in syscall. Check http://golang.org/pkg/syscall/#constants for a complete list of syscall errors. Search "EPIPE" on the page and you will find all the defined errors grouped together.

if err == syscall.EPIPE {
    /* ignore */
}

If you wish to get the actual errno number (although it is pretty useless) you can use a type assertion:

if e, ok := err.(syscall.Errno); ok {
    errno = uintptr(e)
}
英文:

The broken pipe error is defined in the syscall package. You can use the equality operator to compare the error to the one in syscall. Check http://golang.org/pkg/syscall/#constants for a complete list of syscall errors. Search "EPIPE" on the page and you will find all the defined errors grouped together.

if err == syscall.EPIPE {
    /* ignore */
}

If you wish to get the actual errno number (although it is pretty useless) you can use a type assertion:

if e, ok := err.(syscall.Errno); ok {
    errno = uintptr(e)
}

答案2

得分: 10

从go 1.13开始,您可以使用errors.Is而不是类型断言。

if errors.Is(err, syscall.EPIPE) {
  // 管道已断开
}
英文:

As of go 1.13, you can use errors.Is instead of type assertions.

if errors.Is(err, syscall.EPIPE) {
  // broken pipe
}

答案3

得分: -1

拥有除了error接口之外的所有接口已足够进行类型断言或类型切换,以揭示接口所持有的具体类型。

英文:

Having all but an error interface is enough to perform a type assertion or a type switch to reveal the concrete type held by the interface.

huangapple
  • 本文由 发表于 2012年6月13日 03:42:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/11003692.html
匿名

发表评论

匿名网友

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

确定