如何修复linter警告“未检查错误返回值”?

时间:2019-02-14 13:47:17

标签: go linter

我正在使用错误类型值(代码示例中的foo())调用该方法。我不在乎这个结果。严格的代码风格写法是什么? Errcheck linter让我检查此错误。

//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 
}

3 个答案:

答案 0 :(得分:2)

是的,将其分配给通配符变量将是忽略该错误的好方法。但是强烈建议不要忽略(忽略错误)整个实践。这是“ Effective Go”必须说的:

  

有时,您会看到丢弃该错误值以忽略该错误的代码。这是可怕的做法。始终检查错误返回;提供它们是有原因的。

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

答案 1 :(得分:1)

这是惯用的方式:

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

您不应忽略可能的错误。记录或打印到标准输出,但不要忽略它。

答案 2 :(得分:0)

理想情况下,您应该处理该错误,但是如果它使您烦恼,则可以关闭goland的短绒棉布(无论如何,您应该使用它):

enter image description here