polyfloyd / go-errorlint

A source code linter that can be used to find code that will cause problems with Go's error wrapping scheme
MIT License
248 stars 19 forks source link

Warning about comparisons for indirect errors #55

Closed kolyshkin closed 1 year ago

kolyshkin commented 1 year ago

The following code produces no warnings (since v1.4.4, which has #10 fixed).

func CompareUnixErrors() {
        if err := unix.Rmdir("somepath"); err != unix.ENOENT {
                fmt.Println(err)
        }
}

but if we wrap unix.Rmdir into a function:

func rmdir(path string) error {
        return unix.Rmdir(path)
}

func CompareUnixErrors() {
        if err := rmdir("somepath"); err != unix.ENOENT {
                fmt.Println(err)
        }
}

we still get the warning:

unexpected diagnostic: comparing with != will fail on wrapped errors. Use errors.Is to check for a specific error

kolyshkin commented 1 year ago

This might or might not be a dup of #49.

Update: it is not.

kolyshkin commented 1 year ago

This is not specific to unix errors. Here is another example, for io.EOF:

func read(r io.Reader) error {
        var buf [1]byte
        _, err := r.Read(buf[:])
        return err
}

func CompareIoEOFIndirectly(r io.Reader) {
        err := read(r)
        if err != io.EOF {
                fmt.Println(err)
        }
}
polyfloyd commented 1 year ago

Hi!

I have thought about this while developing the linter, but considered this to be too far enough from the original problem and too complex to solve.

As you know, the linter uses a list of permitted function/error combinations to decide whether a raise an issue. But when an error is returned inside a function not part of this allowlist this of course does not work. A solution that achieves what you are suggesting would have to look inside the function being called and build a set of all errors being produced and match it against the list. At this point, I would suggest to use errors.Is to check for errors from such functions. In fact, it might even be desirable to wrap the error anyway to provide context from the wrapping function.

Another solution would be a feature to for custom additions to the allowlist so project specific functions known to be safe could be allowed.

kolyshkin commented 1 year ago

@polyfloyd I guess you are right -- any such function can in fact wrap an error. I do not consider this a bug, thus closing.