为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
MMMHUHU 2022-09-26 14:46:44
我不明白如何处理从网络包接收的错误。我需要知道发生了什么类型的错误才能执行下一步。尝试解析错误消息字符串可能不是正确的方法...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 errorGet "https://example2.com": dial tcp: lookup example2.cometc.
查看完整描述

1 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

您可以检查错误是否与一些已知的错误类型兼容。我是这样做的

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)

}


查看完整回答
反对 回复 2022-09-26
  • 1 回答
  • 0 关注
  • 69 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号