Search code examples
goerror-handlingruntime-error

Idiomatically filtering errors in Go


The error type in Go is quite broad, and the actual type contained can vary by platform as well as between versions. Is it idiomatic to filter errors that we expect by the error's string value, error.Error()?

For example:

_, err := conn.Write(b)
if err != nil {
    if !strings.Contains(err.Error(), "peer reset") {
        log.Print(err)
    }
    return
}

Is there a better way to do this?


Solution

  • errors.Is and errors.As added in more recent versions of Go would now address this problem.