如何正确处理高浪中的网络错误

我不明白如何处理从网络包接收的错误。我需要知道发生了什么类型的错误才能执行下一步。尝试解析错误消息字符串可能不是正确的方法...


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()

    *  } ...

    */

}

例如,我收到的错误消息:


Get "https://example1.com": remote error: tls: internal error

Get "https://example2.com": dial tcp: lookup example2.com

etc.


MMMHUHU
浏览 70回答 1
1回答

FFIVE

您可以检查错误是否与一些已知的错误类型兼容。我是这样做的: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)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go