Closed jamesphillpotts-fr closed 1 day ago
Related Issues
Related Discussions
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
An error matches target if the error's concrete value is assignable to the value pointed to by target
err's type is *myError, target has to point to that, so target's type must be **myError
closing as working as intended
@seankhliao Sure, but the issue in testflag.go
is also what I'm reporting:
if nf := (cmdflag.NonFlagError{}); errors.As(err, &nf) {
and later
if nd := (cmdflag.FlagNotDefinedError{}); errors.As(err, &nd) {
This suffers the same problem as my mistake?
as far as i can tell, cmd/go is using it correctly. you should try to produce a test case that targets testFlags.
It's using exactly the same pattern as my code sample that you pointed out was wrong?
That is, it's passing *cmdflag.NonFlagErorr
not **cmdflag.NonFlagError
The code in cmd/go looks correct to me. The type of the error returned by cmdflag.ParseOne
is NonFlagError
, not *NonFlagError
. The type passed to errors.As
is *NonFlagError
, which will, as expected, match an error of type NonFlagError
.
Further discussion should go to a forum, not the issue tracker. See https://go.dev/wiki/Questions. Thanks.
Go version
1.23.0
Output of
go env
in your module/workspace:What did you do?
Attempting to use
errors.As
to check the content of a custom error type that has not been wrapped.See https://go.dev/play/p/AVAu1v9QGNX for simple reproduction.
It seems that this will never work for errors.As (even though the doc says it should) due to the use of
targetType
in the call to the privateas
function:return as(err, target, val, targetType)
- targetType istyp.Elem()
so this will never satisfy the check in the firstif
statement inas
:As targetType is an element type but
reflectlite.TypeOf(err)
will always be a pointer type.I then thought it should be easy to fix, so started working on a PR, starting with a failing unit test, which failed as expected:
I then attempted to fix this:
What did you see happen?
Unfortunately with the fix in place, the
all.bash
script no longer works, failing with:Debugging, the command line args that are being processed can be seen to be:
The error is from parsing the first non-flag argument.
What did you expect to see?
I expected the fix to work, I think there is a bug in the handling of
cmdflag.NonFlagError
insrc/cmd/go/internal/test/testflag.go
- it seems like without the fix to theerrors.As
function, that if block is actually never being hit even when aNonFlagError
is returned fromcmdflag.ParseOne
- looking at the . I'm not quite sure how that should be fixed, so here's a bug report instead of a PR.