如何修复 linter 警告 `Error return value is not checked`?
How to fix linter warning `Error return value is not checked`?
我正在调用具有错误类型值的方法(代码示例中的 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
}
这是惯用的方式:
err := foo()
if err != nil {
// handle your error here
}
您不应遗漏可能的错误。将其记录或打印到标准输出,但不要忽略它。
是的,将其分配给通配符变量是忽略错误的好方法。但强烈反对整个做法(忽略错误)。以下是 "Effective Go" 对此的看法:
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)
}
理想情况下,您应该处理该错误,但如果它让您烦恼,您可以关闭 goland 中的 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
}
这是惯用的方式:
err := foo()
if err != nil {
// handle your error here
}
您不应遗漏可能的错误。将其记录或打印到标准输出,但不要忽略它。
是的,将其分配给通配符变量是忽略错误的好方法。但强烈反对整个做法(忽略错误)。以下是 "Effective Go" 对此的看法:
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) }
理想情况下,您应该处理该错误,但如果它让您烦恼,您可以关闭 goland 中的 linter(无论如何您都应该使用它):