Tarion
Tarion

Reputation: 17134

Is there a way to find not handled errors in go code?

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?

Upvotes: 5

Views: 3939

Answers (1)

TheGrum
TheGrum

Reputation: 68

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

Upvotes: 4

Related Questions