Filter out broken pipe errors
Asked Answered
A

3

13

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...
Adeliaadelice answered 12/6, 2012 at 19:42 Comment(0)
J
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)
}
Janerich answered 12/6, 2012 at 20:20 Comment(2)
This looks like a winner, I'll give a go.Adeliaadelice
Yes it did. In addition I had to type-assert to net.OpError first, then compare opErr.Err == syscall.EPIPE.Adeliaadelice
R
10

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

if errors.Is(err, syscall.EPIPE) {
  // broken pipe
}
Repent answered 3/10, 2019 at 22:19 Comment(0)
L
-1

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.

Lawsuit answered 12/6, 2012 at 19:56 Comment(1)
That doesn't tell me where the concrete type for this error is held.Adeliaadelice

© 2022 - 2024 — McMap. All rights reserved.