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 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思