tomarrell / wrapcheck

A Go linter to check that errors from external packages are wrapped
https://blog.tomarrell.com/post/introducing_wrapcheck_linter_for_go
MIT License
291 stars 26 forks source link

Ignore errors in closures passed to specific functions #51

Open SOF3 opened 6 days ago

SOF3 commented 6 days ago

I have a utility function like this:

type Slice[T any] []T

func (slice Slice[T]) TryForEach(message string, fn func(T) error) error {
    for _, item := range slice {
        if err := fn(item); err != nil {
            return errors.Wrap(err, message)
        }
    }
    return nil
}

However, when I call this function:

slice.TryForEach("message", func(value T) error {
    return otherpkg.DoSomething(value)
}

I get an error for not wrapping DoSomething.

TryForEach actually already wraps the error. It would be useful to have an ignore directive like this:

wrapcheck:
  ignoreClosureInArgList:
    - func: "TryForEach"
      param: "fn"

such that the lint is disabled for top-level return statements (and not including nested closures) in closures if the closure is directly passed as the fn parameter for a function matching TryForEach.

SOF3 commented 6 days ago

I'm happy to contribute this feature myself, would just like to hear some opinions on the design first.

tomarrell commented 6 days ago

Hmm, that is an interesting use case. Quite specific, it seems.

I'm not opposed to it, but I'm currently thinking of the value versus adding a line level ignore. Is this something that happens enough to you that it's worth the implementation effort for you?

SOF3 commented 6 days ago

Well, I use the TryForEach function a lot in the implementation of a certain interface in my project, so I have to add //nolint:wrapcheck above the whole function for every implementation of this interface. I agree this is a bit niche; would be great if anyone could propose a more reusable ignore rule.