How to detect error values that are never used

137 views Asked by At

I'm looking for a way to to find occurrences of this error "handling" that doesn't do anything with the first error:

example:

func handler() {
   var myErr error

   myErr = doSomething() //Warn me about this please

   myErr = doSomethingElse()

   if myErr != nil {
      return
   }

}

func doSomething() error {
    return errors.New("an example error")
}

func doSomethingElse() error {
    return errors.New("an example error")
}

I would like to be warned that I haven't used the error after the first call to svc.DoSomething() because its effectively overwritten and ignored.

I have tried enabling all code inspections in goland 2021.3 and have tried staticcheck and have searched for an existing linter.

I believe it should show SA4006 after the first call to svc.DoSomething() which works fine in VSCode.

2

There are 2 answers

2
aureliar On BEST ANSWER

I'd suggest the ineffassign linter: https://github.com/gordonklaus/ineffassign

It can be used as a standalone tool or via golangci-lint: https://golangci-lint.run/usage/linters/

It's not gonna check only for error, but for all useless assignments (ie that aren't used latter on) like in your example.

1
newbie On

VSCode does the same thing.

enter image description here

After I use this variable:

enter image description here

Doc: https://pkg.go.dev/golang.org/x/tools/internal/typesinternal#UnusedVar

Diagnostic Tools: https://github.com/golang/vscode-go/wiki/tools#diagnostics