F.J.
F.J.

Reputation: 111

How to handle net errors in golang properly

I do not get how one can handle errors receiving from the net package. I need to know what kind of error occurred to do the next step. Trying to parse the error message string is probably not the right way...

response, err := data.httpClient.Get("https://" + domain)
if err != nil {             
    fmt.Println("[!] error: ", err)
    /* 
    *  I want something like this in pseudo code:
    *  if error == DnsLookupError {
    *      action1()
    *  } else if error == TlsCertificateError {
    *      action2()
    *  } else if error == Timeout {
    *      action3()
    *  } ...
    */
}

Error messages I receive for example:

Get "https://example1.com": remote error: tls: internal error
Get "https://example2.com": dial tcp: lookup example2.com
etc.

Upvotes: 7

Views: 3469

Answers (1)

Roland Illig
Roland Illig

Reputation: 41617

You can check whether the error is compatible with a few well-known error types. I did it like this:

func classifyNetworkError(err error) string {
    cause := err
    for {
        // Unwrap was added in Go 1.13.
        // See https://github.com/golang/go/issues/36781
        if unwrap, ok := cause.(interface{ Unwrap() error }); ok {
            cause = unwrap.Unwrap()
            continue
        }
        break
    }

    // DNSError.IsNotFound was added in Go 1.13.
    // See https://github.com/golang/go/issues/28635
    if cause, ok := cause.(*net.DNSError); ok && cause.Err == "no such host" {
        return "name not found"
    }

    if cause, ok := cause.(syscall.Errno); ok {
        if cause == 10061 || cause == syscall.ECONNREFUSED {
            return "connection refused"
        }
    }

    if cause, ok := cause.(net.Error); ok && cause.Timeout() {
        return "timeout"
    }

    return sprintf("unknown network error: %s", err)
}

Upvotes: 8

Related Questions