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

如何获取要在错误处理中使用的错误类型

如何获取要在错误处理中使用的错误类型

Go
大话西游666 2022-09-19 14:46:25
如果您这样做:_, err := http.Get("google.com")if err != nil {    log.Fatal(err)}你得到的输出:2021/08/05 15:42:18 Get "google.com": unsupported protocol scheme ""我想知道如何获取错误类型,以便我可以像这样处理错误:if errors.Is(err, "unsupported protocol scheme") {    //add protocol scheme to url string}我试过 fmt。Printf(“%#v”,错误),它给出了:&url.Error{Op:"Get", URL:"google.com", Err:(*errors.errorString)(0xc000098c40)}断续器打印(“%T”)给出:*url.Error编辑:如果你投了反对票,我非常感谢你的想法。
查看完整描述

2 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

var e *url.Error

if errors.As(err, &e) && strings.HasPrefix(e.Err.Error(), "unsupported protocol scheme") {

    //add protocol scheme to url string

}

https://play.golang.org/p/VKpMfrBp_EF


请注意,与非标准化字符串的比较不应被视为面向未来的。例如,如果 Go 的未来版本决定更改该错误消息的措辞,则您的代码将中断。


虽然Go确实承诺跨版本兼容,但我不认为这个承诺延伸到字符串内容。


查看完整回答
反对 回复 2022-09-19
?
森栏

TA贡献1810条经验 获得超5个赞

可用于返回字符串。并检查它是否包含一个辣键,如下所示:err.Error()


if err = db.Ping(); err != nil {

    switch {

    case strings.Contains(err.Error(), "connection refused"):

         // handle connection refused. for example:

         cmd := exec.Command("sudo", "service", "mariadb", "start")          

         _ = cmd.Run()

       

    default:

         log.Println("unknown kind of this error", err)

    }

}

在你的情况下,你可以尝试这样的事情:


err := http.Get(url)


if strings.Contains(err.Error(), "unsupported protocol scheme") {

    //add protocol scheme to url string

}


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

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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