Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wrong MatchError behavior when the error has an Is function #452

Open
marten-seemann opened this issue Jun 23, 2021 · 2 comments
Open

wrong MatchError behavior when the error has an Is function #452

marten-seemann opened this issue Jun 23, 2021 · 2 comments

Comments

@marten-seemann
Copy link
Contributor

I have an error that (in its minimal form) looks like this:

type MyError struct {
	ErrorCode  int
}

func (e *MyError) Error() string {
	return fmt.Sprintf("Error %d", e.ErrorCode)
}

func (e *MyError) Is(target error) bool {
	_, ok := target.(*MyError)
	if ok {
		return true
	}
	return target == net.ErrClosed
}

Now I have the following test case:

It("recognizes different errors", func() {
	err1 := &qerr.MyError{
		ErrorCode:    1,
		ErrorMessage: "foo",
	}
	err2 := &qerr.MyError{
		ErrorCode:    2,
		ErrorMessage: "bar",
	}
	Expect(err1).ToNot(MatchError(err2))
})

This test fails because the second part of this if statement:

if isError(expected) {
return reflect.DeepEqual(actualErr, expected) || errors.Is(actualErr, expected.(error)), nil
}

In my understanding, Go's errors.Is is supposed to be used to one error has the same type as another error, i.e. perform

myErr, ok := err.(*MyError)

recursively, unwrapping err using errros.Unwrap until a match is found.

@marten-seemann marten-seemann changed the title wrong MatchError behavior when the error has an Is definition wrong MatchError behavior when the error has an Is function Jun 23, 2021
@marten-seemann
Copy link
Contributor Author

Related to my earlier issue #439.

Maybe the solution is to remove the problematic second part of the if statement I describe above, and actually implement the BeAssignableToError?

@onsi
Copy link
Owner

onsi commented Jun 23, 2021

hey @marten-seemann

you mentioned:

In my understanding, Go's errors.Is is supposed to be used to one error has the same type as another error, i.e. perform

but I don't think I'm drawing the same conclusion after reading the go docs.

They seem to be saying that if an error type defines Is then that function is called and honored when computing equivalence regardless of type. (Their example with the MyError type being equivalent to fs.ErrExist seems to make this explicit) - am I missing something?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants