比较Go语言中的错误

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

Comparing errors in Go

问题

在我的测试文件中,我试图将检测到的实际错误与预期错误进行比较。然而,这个比较结果为false,我不确定为什么会这样。即使我创建两个完全相同的错误并进行比较,也会出现这种情况。

代码片段:

func TestCompareErrors(t *testing.T) {
    if fmt.Errorf("Test Error") != fmt.Errorf("Test Error") {
        t.Errorf("Test failed")
    }
}

这将导致"Test failed"的结果。

英文:

In my test file, I am trying to compare an actual error detected with the expected error. However, this comparison evaluates to false, and I'm unsure why. This even happens when I create two identical errors and compare them.

Code snippet:

func TestCompareErrors(t *testing.T) {
    if fmt.Errorf("Test Error") != fmt.Errorf("Test Error") {
        t.Errorf("Test failed")
    }
}

This results in "Test failed"

答案1

得分: 3

你正在比较两个不同的值,它们恰好具有相同的错误消息。你想要比较预定义的错误值,就像你对常见值(如io.EOF)进行比较一样。

var errTest = fmt.Errorf("test error")

func do() error {
    return errTest
}

func main() {
    err := do()
    if err == errTest {
        log.Fatal("received error: ", err)
    }
}

你可以阅读《错误是值》以获得更详细的解释。

如果你需要在错误中提供更多信息,你可以创建自己的错误类型。然后,你可以将任何你想要的信息附加到错误上,并通过类型断言检查该类型的错误。

type myError string

func (e myError) Error() string {
    return string(e)
}

func do() error {
    return myError("oops")
}

func main() {
    err := do()
    if err, ok := err.(myError); ok {
        log.Fatal("received myError: ", err)
    }
}
英文:

You are comparing two different values which happen to have the same error message. You want to compare predefined error values, just like you would with common values like io.EOF.

http://play.golang.org/p/II8ZeASwir

var errTest = fmt.Errorf("test error")

func do() error {
	return errTest
}

func main() {
	err := do()
	if err == errTest {
		log.Fatal("received error: ", err)
	}

}

You can read "Errors are Values" for a more in-depth explanation.

If you need to provide more information with the error, you can create your own error type. You can then attach whatever information you want to the error, and check for that type of error via a type assertion.

type myError string

func (e myError) Error() string {
	return string(e)
}

func do() error {
	return myError("oops")
}

func main() {
	err := do()
	if err, ok := err.(myError); ok {
		log.Fatal("received myError: ", err)
	}
}

答案2

得分: 3

使用reflect.DeepEqual来比较值。

if reflect.DeepEqual(fmt.Errorf("Test Error"), fmt.Errorf("Test  Error")) {
    // 错误值相同。
}

playground中的示例

英文:

Use reflect.DeepEqual to compare values.

if reflect.DeepEqual(fmt.Errorf("Test Error"), fmt.Errorf("Test  Error")) {
    // the error values are same.
}

Example in playground

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

发表评论

匿名网友

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

确定