英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论