Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Add option for strict checking of if statement declares #238

Open
kf6nux opened this issue Jan 26, 2024 · 0 comments
Open

Proposal: Add option for strict checking of if statement declares #238

kf6nux opened this issue Jan 26, 2024 · 0 comments

Comments

@kf6nux
Copy link

kf6nux commented Jan 26, 2024

Problem Statement

A common pattern of if-statement declarations is to declare an error and then check it.

e.g.

if err := myfunc(); err != nil {

I saw someone surprised that errcheck didn't catch the following bug

if err2 := myfunc(); err != nil {
  err = errors.Join(err, err2)

While there may be valid use-cases for declaring an error interface in an if statement before the if expression and then not immediately checking it, I think the common expectation/use is that people are immediately checking the errors they're declaring.

Proposal

  • Add a flag like the existing -blank for if declares. Maybe -ifdeclares
  • When checking if declares, errcheck should
  1. identify all errors declared in the if statement before the if expression
  2. produce a warning/failure if the if-expression doesn't contain all of those errors

Open Question

Should this be enabled by default? Maybe we can run the check across stdlib as a test.

Test case

The following Go file should produce a warning/failure when if-declares are checked

package main

import (
	"errors"
	"fmt"
)

func main() {
	err := errors.New("a")
	if err2 := errors.New("b"); err != nil {
		err = errors.Join(err, err2)
	}
	fmt.Println(err.Error())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant