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

如果您这样做:


_, 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

编辑:如果你投了反对票,我非常感谢你的想法。


大话西游666
浏览 187回答 2
2回答

斯蒂芬大帝

var e *url.Errorif 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确实承诺跨版本兼容,但我不认为这个承诺延伸到字符串内容。

森栏

可用于返回字符串。并检查它是否包含一个辣键,如下所示: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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go