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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵