特定错误处理的行为不明确

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

Unclear behavior at specific error handling

问题

我正在尝试处理特定的错误,但对于其行为感到惊讶。

示例:

如果我使用

  1. if err == errors.New("something") {}

即使errnil,它也会返回true

如果我使用

  1. if err.String() == "something"

errnil时,它会引发恐慌。

我真的期望

  1. err == errors.New("something")

能够正常工作,但我不确定为什么它返回true

更多代码:

这里有一些代码来阐明问题(Play):

  1. package main
  2. import "fmt"
  3. import "errors"
  4. func main() {
  5. e := errors.New("error")
  6. //我期望这将返回true
  7. if e == errors.New("error") {
  8. fmt.Println("Hello, playground")
  9. }
  10. }
英文:

I'm trying to handle specific errors but I'm surprised about the behavior.

Examples:

If I use

  1. if err == errors.New("something"){}`

it returns true, even if err is nil.

If I use

  1. if err.String() == "something"`

it panics when err is nil.

I really expected

  1. err == errors.New("something")`

to work and I'm not sure why it returns true.

Some more code:

Here is some code to clarify the question (Play):

  1. package main
  2. import "fmt"
  3. import "errors"
  4. func main() {
  5. e := errors.New("error")
  6. //I'm expecting this to return true
  7. if e == errors.New("error") {
  8. fmt.Println("Hello, playground")
  9. }
  10. }

答案1

得分: 6

你可以做以下事情:

  • 比较 err.Error(): if err != nil && err.Error() == "something"
  • 使用全局变量来表示错误

以下是第二种解决方案的示例代码:

  1. package my_package
  2. var ErrSmth = errors.New("something")
  3. func f() error {
  4. return ErrSmth
  5. }
  1. package main
  2. import "my_package"
  3. func main() {
  4. err := f()
  5. if err == my_package.ErrSmth {
  6. // 做一些操作
  7. }
  8. }

第二种解决方案是处理特定错误的方式,io 包也是这样处理的。

英文:

What you can do:

  • compare err.Error(): if err != nil && err.Error() == "something"
  • use global variables for your errors

Here is an example for the second solution:

  1. package my_package
  2. var ErrSmth = errors.New("something")
  3. func f() error {
  4. return ErrSmth
  5. }

  1. package main
  2. import "my_package"
  3. func main() {
  4. err := f()
  5. if err == my_package.ErrSmth {
  6. // Do something
  7. }
  8. }

The second solution is the way specific errors are handled with the io package.

huangapple
  • 本文由 发表于 2014年7月30日 23:25:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/25040780.html
匿名

发表评论

匿名网友

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

确定