Skip to content

proposal: cmd/vet, x/tools/go/analysis/passes/errorsastype: detect misuse of AsType in else if #78889

Description

@mateusz834

Proposal:

  • Expose the internal errorsastype analyzer from gopls as x/tools/go/analysis/passes/errorsastype
  • Make use of it in go vet analyzers suite.

#78889 (comment)

Rationale

So recently in a code review I have suggested:

var err error

if err, ok := errors.AsType[*FooErr](err); ok {
    doSth(err)
} else if err, ok := errors.AsType[*BarErr](err); ok {
    doSth(err)
}

And at first glance it looks like a completely valid code, but it is not.

The err passed to second errors.AsType is not the err declared in the first line, but it is the err declared in the first if stmt (which is always going to be a concrete-type nil (zero-val to be precise)).

I also don't think that any "shadowing" analyzer would help here, for example consider the output of #75368.

Image

I understand this output as err in if and else if are shadowing the global err directly, bot not that the err in else if is shadowing the err in if and so on.

Since errors.AsType is a new thing I don't think we can have data to back this up with, but might be worth detecting since it seems like a easy thing to do by mistake.

CC @adonovan

Metadata

Metadata

Assignees

Labels

FixPendingIssues that have a fix which has not yet been reviewed or submitted.ProposalProposal-HoldToolsThis label describes issues relating to any tools in the x/tools repository.

Type

No type

Projects

Status
Hold

Relationships

None yet

Development

No branches or pull requests

Issue actions