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

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

Unclear behavior at specific error handling

问题

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

示例:

如果我使用

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

即使errnil,它也会返回true

如果我使用

if err.String() == "something"

errnil时,它会引发恐慌。

我真的期望

err == errors.New("something")

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

更多代码:

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

package main

import "fmt"
import "errors"

func main() {
    e := errors.New("error")
    //我期望这将返回true
    if e == errors.New("error") {
        fmt.Println("Hello, playground")
    }
}
英文:

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

Examples:

If I use

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

it returns true, even if err is nil.

If I use

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

it panics when err is nil.

I really expected

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):

package main

import "fmt"
import "errors"

func main() {

    e := errors.New("error")
    //I'm expecting this to return true
	if e == errors.New("error") {
	    fmt.Println("Hello, playground")
	}
}

答案1

得分: 6

你可以做以下事情:

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

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

package my_package

var ErrSmth = errors.New("something")

func f() error {
    return ErrSmth
}
package main

import "my_package"

func main() {
    err := f()
    if err == my_package.ErrSmth {
         // 做一些操作
    }
}

第二种解决方案是处理特定错误的方式,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:

package my_package

var ErrSmth = errors.New("something")

func f() error {
    return ErrSmth
}

package main

import "my_package"

func main() {
    err := f()
    if err == my_package.ErrSmth {
         // Do something
    }
}

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:

确定