在Go程序中,有没有办法检查未处理的错误?

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

Any way to check for un-handled errors in a Go program?

问题

考虑以下代码:

package main

import (
	"errors"
	"fmt"
)

func foo() error {
	return errors.New("Danger!")
}

func main() {
	foo()
	fmt.Println("I don't have a care in the world!")
}

如果有一种简单的方法可以查看是否处理了foo()可能出现的错误,那将是很好的。Go语言是否有内置的方法来检查程序或源文件中是否有未处理的错误呢?

英文:

Consider the following:

package main

import (
	"errors"
	"fmt"
)

func foo() error {
	return errors.New("Danger!")
}

func main() {
	foo();
	fmt.Println("I don't have a care in the world!")
}

It would be nice if there was an easy way to see that possible errors from foo() are not being handled. Does Go have a built-in way to check programs/source files for errors that nothing has been done with?

答案1

得分: 6

Go语言本身没有内置的方法来实现这个功能,但是有一个由Kamil Kisiel开发的第三方工具可以实现。你只需要执行go get github.com/kisielk/errcheck命令,然后在你的$GOPATH路径下执行bin/errcheck your/import/path命令,它会输出一个忽略错误的调用列表。(我刚刚在一个项目上尝试了一下,嗯,也许我对此并不像我想象的那样100%可靠。)

如果你喜欢这个工具,你可能还会喜欢go vet的检查功能,以及lint包在Google内部用于风格检查的工具。

英文:

Go does not have a built-in way to do that, but there's a third-party tool by Kamil Kisiel that does. Just go get github.com/kisielk/errcheck then run bin/errcheck your/import/path from your $GOPATH and it will spit out a list of calls with ignored errors. (I just tried it on a project and, hrm, perhaps I'm not as 100% reliable about it as I thought.)

If you like it, you might also like go vet's checks, and the lint package used within Google for style checks.

答案2

得分: 4

你可以使用errcheck

$ errcheck github.com/your/package

它会在你忽略返回的错误时提醒你。我认为,如果你使用一个好的编辑器(能显示函数签名),这种情况应该是很少见的。

英文:

You can use errcheck:

$ errcheck github.com/your/package

It will let you know when you are ignoring returned errors. I would argue that this should mostly be rare if you are using a decent editor (that shows you function signatures).

huangapple
  • 本文由 发表于 2014年7月6日 09:59:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/24592068.html
匿名

发表评论

匿名网友

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

确定