Skip to content

x/tools/go/analysis: show invalid usage of errors.As() #61342

Open
@guettli

Description

@guettli

Is your feature request related to a problem? Please describe.

This fails:

package main

import (
	"errors"
	"fmt"
	"os"
)

type CustomError struct {
	Msg string
}

func (e CustomError) Error() string {
	return e.Msg
}

func main() {
	// You can replace this with your actual function which returns an error
	err := fmt.Errorf("this is a wrapped error: %w", &CustomError{Msg: "custom error"})

	customErr := CustomError{}
	if errors.As(err, &customErr) {
		// Here you can handle your custom error
		fmt.Println("This is a custom error:", customErr.Msg)
	} else {
		// Here you handle all other errors
		fmt.Println(":-(  sad - not exptected")
		fmt.Println(err)
		os.Exit(1)
	}
}

Describe the solution you'd like

I would like to get a warning if I provide a pointer to a struct to errors.As().

Changing the line to this works:

customErr := &CustomError{}

That's easy to get wrong, and it takes some time to find the error.

Describe alternatives you've considered

I considered the alternative: don't make mistakes. But sorry, I am not perfect.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureRequestIssues asking for a new feature that does not need a proposal.NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.ToolsThis label describes issues relating to any tools in the x/tools repository.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions