如何检查恢复中的确切错误类型?

huangapple go评论92阅读模式
英文:

How to check the exact type of error in recover?

问题

我正在按照这个例子进行操作:

https://www.socketloop.com/tutorials/golang-smarter-error-handling-with-strings-contains-function

 if !strings.Contains(err.Error(), "timed out") {
 	fmt.Printf("resulting error not a timeout: %s", err)
 }

然而,如果我在我的代码中这样做,我会得到以下错误:

> err.Error未定义(类型interface {}是没有方法的接口)

我想知道我在这里做错了什么,以及如何检查一个确切的错误(在我的情况下,我想从错误"slice bounds out of range"中恢复)

最好,

英文:

I'm following this example here:

https://www.socketloop.com/tutorials/golang-smarter-error-handling-with-strings-contains-function

 if !strings.Contains(err.Error(), "timed out") {
 	fmt.Printf("resulting error not a timeout: %s", err)
 }

However, if I do that in my code I will get this

> err.Error undefined (type interface {} is interface with no methods)

I wonder what I'm doing wrong here, and how should I check for an exact error (in my case I want to recover from the error "slice bounds out of range")

Best,

答案1

得分: 5

使用类型断言来获取error https://play.golang.org/p/BryV7YfZHS

defer func(){
    err := recover().(error)
    fmt.Println(err.Error())
}()

a := make([]int, 0)
a[1] = 0

但我建议你不要这样做。首先,你不应该使用recover。在几乎所有情况下,这意味着你做错了什么。相反,修复导致panic的代码。

其次,不要使用字符串匹配来确定错误的原因。有很多原因说明这样做是不好的,但我只想说这不是Go的做事方式。我理解你可能正在使用一些只能这样做的API,但尽量找到更好的方法。使用类型断言、类型切换来获取确切的错误类型,然后从那里继续。

英文:

Use type assertion to get error https://play.golang.org/p/BryV7YfZHS

defer func(){
    err := recover().(error)
    fmt.Println(err.Error())
}()

a := make([]int, 0)
a[1] = 0

But I suggest you don't do that. First, you should not use recover. In almost all cases that means you're doing something wrong. Instead, fix the code that panics.

Second, don't use string matching to determine the cause of the error. There're many reasons why it's bad but I will just say that it's not the Go way of doing things. I understand that you may be using API that just doesn't leave you a choice but try to find a better way. Use type assertion, type switch to get the exact error type and go from there.

huangapple
  • 本文由 发表于 2016年3月13日 19:55:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/35969911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定