Skip to content

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

@kf6nux

Description

@kf6nux

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())
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions