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
249 stars 19 forks source link

Getting non-wrapping format verb for fmt.Errorf. While using custom errors. #16

Closed aNickPlx closed 3 years ago

aNickPlx commented 3 years ago

I found this bug while working on a package that has custom error objects. While calling a third party package, I check for errors and return a wrapped custom error from my package while also returning the third party error as a string appended to the error message.

This might be easier to explain with an example.

If we look at the file errorlint/testdata/src/fmterrorf/fmterrorf.go there is a test case that requires at least one wrap on fmt.Errorf

func ErrorAtLeastOneWrap() error {
    err1 := errors.New("oops1")
    err2 := errors.New("oops2")
    err3 := errors.New("oops3")
    return fmt.Errorf("%v, %w, %v", err1, err2, err3)
}

However, if we adjust the testcase a little bit, we get the error unexpected diagnostic: non-wrapping format verb for fmt.Errorf. Use `%w` to format errors

func ErrorAtLeastOneWrapCustomError() error {
    err1 := errors.New("oops1")
    err2 := MyError{}
    err3 := errors.New("oops3")
    return fmt.Errorf("%v, %w, %v", err1, err2, err3)
}

I would like to keep wrapping the package's custom errors as they are already part of the public API.

polyfloyd commented 3 years ago

Yes, that is indeed a bug. Thank you for your detailed report and a fix! :)