edwardmp
edwardmp

Reputation: 6591

Comparing errors in Go

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"

Upvotes: 2

Views: 3108

Answers (2)

Fallen
Fallen

Reputation: 4565

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

Upvotes: 3

Mr_Pink
Mr_Pink

Reputation: 109347

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

Upvotes: 3

Related Questions