dongzhan7909 2017-05-10 16:26
浏览 25
已采纳

有没有办法找到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条回答 默认 最新

  • dongposhi8677 2017-05-10 20:07
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何证明高斯噪声的包络公式
  • ¥150 寻找王者荣耀开发作者,合作或者解答
  • ¥15 乳腺癌数据集 相关矩阵 特征选择
  • ¥15 我的游戏账号被盗取,请问我该怎么做
  • ¥15 通关usb3.0.push文件,导致usb频繁断连
  • ¥15 有没有能解决微信公众号,只能实时拍照,没有选择相册上传功能,我不懂任何技术,,有没有给我发个软件就能搞定的方法
  • ¥15 Pythontxt文本可视化
  • ¥15 如何基于Ryu环境下使用scapy包进行数据包构造
  • ¥15 springboot国际化
  • ¥15 搭建QEMU环境运行OP-TEE出现错误