wrapcheck icon indicating copy to clipboard operation
wrapcheck copied to clipboard

consider flagging errors.Wrap(err) where err is known to be nil

Open jkowalski opened this issue 3 years ago • 5 comments

I found several cases in my codebase (https://github.com/kopia/kopia/pull/747) that follow the following buggy pattern:

err := doSomething()
if err != nil {
  return result, errors.Wrap(err, "something failed")
}

if somethingElse {
  return result, errors.Wrap(err, "something else failed")
}

The second errors.Wrap() is incorrect, because it's not wrapping any error (but it's easy to copy/paste it as such).

This is quite hard to spot in code reviews because lines that return errors will always have errors.Wrap() and it looks ok at first glance, until you notice that in this case is err is always nil. Because errors.Wrap(nil, "something") always returns nil this one returns success, which is unintended.

Based on flow analysis, it should be possible to determine that err == nil in this case, and it would be really amazing if the linter could flag this pattern is as misuse.

jkowalski avatar Dec 25 '20 04:12 jkowalski

Hmm interesting, definitely seems doable. I can take a look when I get some time.

Cheers for bringing it up.

tomarrell avatar Jan 21 '21 10:01 tomarrell

There is another version of this that I find a lot in code reviews that would be handy to catch with this linter...

Common sql error checking:

if rows.Err() != nil {
  return result, errors.Wrap(err, "something failed")
}

Because err is declared above this statement, the compiler doesn't raise any issues.

Maybe this is out of scope for this linter and should be a dedicated linter?

jtwatson avatar Nov 24 '21 01:11 jtwatson

Hello @tomarrell, any news on this ? That would be tremendously helpful to have such functionality

kepelletier avatar Nov 26 '21 08:11 kepelletier

G'day, I think both of these cases could be implemented neatly within this linter as it already has the definition checking there.

As far as timeline, I can't give anything concrete, however I will start looking into this next as I get some time. If you want it ASAP, I'm quite responsive to PR's.

Thanks!

tomarrell avatar Nov 26 '21 11:11 tomarrell

Thanks a lot for your answer. I'm looking forward to this new feature!

kepelletier avatar Dec 02 '21 13:12 kepelletier