有没有办法在Go代码中找到未处理的错误?

huangapple go评论97阅读模式
英文:

Is there a way to find not handled errors in go code?

问题

假设有以下代码:

func main() {
    doStuff()
}

听起来不错,直到你的程序运行时没有任何错误,但却没有执行任何操作,因为你忘记了doStuff()实际上是这样的:

func doStuff() error {
    // ...
    return errors.New("woops!")
}

我们应该这样做:

func main() {
    err := doStuff()
    if err != nil {
        panic(err)
    }
}

或者至少(为了明显起见):

func main() {
    _ = doStuff()
}

有很多Go工具可以用来检查代码中未处理的错误返回值。是否有一种简单的方法来检查我的代码中是否有未处理的错误返回值?

英文:

Let's assume the following code:

func main() {
    doStuff()
}

Sound good, until your program runs without any error but does nothing because you just forgot that doStuff() actually looks like:

func doStuff() error {
    // ...
    return errors.New("woops!")
}

What we should do ist:

func main() {
    err := doStuff()
    if err != nil {
        panic(err)
    }
}

Or at least (to make it obvious):

func main() {
    _ = doStuff()
}

There are so many go tools out there like. Is there a simple way to check my code for not handled error return values?

答案1

得分: 4

如@eugecm建议的那样,github.com/kisielk/errcheck可以实现这个功能,github.com/GoASTScanner/gas也可以。此外,github.com/alecthomas/gometalinter可以方便地下载一系列的代码检查工具并并行运行它们,其中包括前面提到的两个工具。

所以,

go get github.com/alecthomas/gometalinter
gometalinter --install
gometalinter

会下载gometalinter,并安装一些错误和风格检查工具,并并行运行它们,然后报告结果。

你的示例中相关的结果会是这样的:

main.go:13::warning: Errors unhandled.,LOW,HIGH (gas)
main.go:13::warning: error return value not checked (doStuff()) (errcheck)

我推荐使用gometalinter,因为它会给出上述的结果。如果只是在命令行中运行errcheck,它只会显示main.go:13:10 doStuff()(因为errcheck只检查未处理的错误返回值,所以实际上不需要额外的信息)。

英文:

As @eugecm suggested, github.com/kisielk/errcheck will do this, as will github.com/GoASTScanner/gas . Also, github.com/alecthomas/gometalinter makes it easy to download a collection of linters and run them in parallel, and includes both of the above.

So,

go get github.com/alecthomas/gometalinter
gometalinter --install
gometalinter

would download gometalinter, which will then install a number of error and style checkers and run them in parallel, reporting the results.

The relevant results from your example would be like:

main.go:13::warning: Errors unhandled.,LOW,HIGH (gas)
main.go:13::warning: error return value not checked (doStuff()) (errcheck)

I recommend gometalinter because it gives results like the above, where running errcheck on a bare command just says main.go:13:10 doStuff() (because errcheck is a program that only checks for unchecked error return values, so no additional information is really necessary).

huangapple
  • 本文由 发表于 2017年5月11日 00:26:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/43898074.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定