How to fix linter warning `Error return value is not checked`?
Asked Answered
B

3

18

I'm calling the method with error type value (foo() in code example). I don't care this result. What's the rigth code style way to write? Errcheck linter makes me check this error.

//for example, same method may be called from imported entity
func foo() error {
   if err := someFunction(); err != nil {
       return err
   }
   return nil
}

func process() {
   //linter doesn't like this
   foo()

   //this way leads to unused variable error
   err := foo()

   //is this clean way?
   _ = foo()

  return 
}
Beabeach answered 14/2, 2019 at 13:47 Comment(0)
S
12

Yes, assigning it to a wildcard variable would be a good way to ignore the error. But the whole practice (of ignoring errors) is strongly discouraged. Here's what "Effective Go" has to say about this:

Occasionally you'll see code that discards the error value in order to ignore the error; this is terrible practice. Always check error returns; they're provided for a reason.

   // Bad! This code will crash if path does not exist.
    fi, _ := os.Stat(path)
    if fi.IsDir() {
        fmt.Printf("%s is a directory\n", path)
    }
Sail answered 14/2, 2019 at 13:54 Comment(0)
S
9

This is the idiomatic way:

err := foo()
if err != nil {
  // handle your error here
}

You should not omit a possible error. Log it or print it to stdout, but do not ignore it.

Silvie answered 14/2, 2019 at 13:54 Comment(0)
I
0

Ideally you should handle the error but if it annoys you, you could turn off the linter, in goland (which you should be using anyway):

enter image description here

Introduction answered 14/2, 2019 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.