Description
The interfaces for errors.Is
and errors.As
seem stable and complete. Unfortunately, it requires reading through the godoc to ensure that your custom error type correctly implements interface{ As(interface{}) bool }
, interface{ Is(error) bool }
, or interface{ Unwrap() error }
. This can lead to implementation bugs that fail pathologically.
Instead of exposing these symbols, as was proposed in #39539, we can add a vet check to ensure that error
s with Is
, As
, or Unwrap
methods implement the correct interfaces. This is not a requirement that all error
s implement Is
, As
, and Unwrap
, but simply that if the symbol exists, the syntax matches.
Technically, this is not required, as you can use an anonymous type to perform this check at compile time. But this is ungainly, not automatic, and fails to the same typographical issues due to its distributed implementation:
var (
_ = (interface{ As(interface{}) bool })(myError{})
_ = (interface{ Is(error) bool })(myError{})
_ = (interface{ Unwrap() error })(myError{})
_ = error(myError{})
Activity
carnott-snap commentedon Aug 6, 2020
@ianlancetaylor: can you add this to the proposals project?
ianlancetaylor commentedon Aug 6, 2020
@carnott-snap Done.
urandom2 commentedon Apr 14, 2021
did this get lost in the incoming stack?
ianlancetaylor commentedon Apr 14, 2021
The incoming stack has more than 200 issues in it, so it's going to take a while to get through them all.
See https://github.com/golang/go/projects/1 .
rsc commentedon Apr 21, 2021
This proposal has been added to the active column of the proposals project
and will now be reviewed at the weekly proposal review meetings.
— rsc for the proposal review group
neild commentedon Apr 21, 2021
I don't object to
cmd/vet
checking the signature ofAs
/Is
/Unwrap
methods for types that implement theerror
interface; it seems unlikely to have significant false positives. However, the best way to ensure an error implements these interfaces correctly is to write a test for the error, because a test will validate not only the method signature but the implementation.gopherbot commentedon Apr 22, 2021
Change https://golang.org/cl/312829 mentions this issue:
passes/stdmethods: warn when an error has an unexpected Is, As, or Unwrap method.
rsc commentedon Apr 28, 2021
Based on the discussion above, this proposal seems like a likely accept.
— rsc for the proposal review group
timothy-king commentedon Apr 29, 2021
Tested golang.org/cl/312829 against a large Go codebase that uses Is, As and Unwrap. No findings so no false positives.
2 remaining items
passes/stdmethods: warn when an Is, As, or Unwrap has the wrong signa…
gopherbot commentedon May 20, 2021
Change https://golang.org/cl/321389 mentions this issue:
cmd: go get golang.org/x/tools/analysis@49064d23 && go mod vendor
cmd: go get golang.org/x/tools/analysis@49064d23 && go mod vendor