Hello everyone. In relation to standard errors package, I wanted to ask
about safe ways of implementing Is(target error) bool. The current
documentation
(https://cs.opensource.google/go/go/+/refs/tags/go1.20.6:src/errors/wrap.go;l=35)
says the following:
// An error type might provide an Is method so it can be treated as
equivalent
// to an existing error. For example, if MyError defines
//
// func (m MyError) Is(target error) bool { return target == fs.ErrExist }
This seems wrong and actually leads users in the wrong direction, as if
someone implements an error type like "type MyErrs []error" then it's
sufficient to make that implementation panic, so the documentation is
leading users to create panic-prone code. While it's true that interfaces
are comparable, concrete types implementing them may not, and the error
will happen at runtime.
Note that the code for the Is function in errors package actually uses
reflectlite.TypeOf(target).Comparable()
to avoid these panics, but that as users do not have access to reflectlite
and, even if they do, the documentation is not warning against these
possible panics, then it's very easy to make mistakes. Of course, nil
comparisons are ok, because the comparison is of the value of the
interface, not the value of the concrete type.
I propose: consider changing the documentation to warn users against this
possible problem when implementing the Is method of their own error types.
My question to the community: how do you currently go about this issue.
Thank you.
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/1fce8a3e-bcd2-41fc-b2e1-02fd70450c09n%40googlegroups.com.