Home > Enterprise >  (*testing.common).Errorf does not support error-wrapping directive %w
(*testing.common).Errorf does not support error-wrapping directive %w

Time:12-29

I was cloning a private go project.

And got below error on the code editor and when running golangci-lint.

code editor screenshot error

golangci-lint screenshot error

The sample code is this:

func TestAService(t *testing.T) {
    ...
    err := service.AService()
    if err != nil {
        t.Errorf("Error on executing the test cases %w", err)
    }
}

The go project runs fine on other laptop, but the one I use it has this error.

The go version used by both laptop are: go 1.17

CodePudding user response:

The screenshots you post aren't errors, they're warnings from your IDE about potential problems in your code.

But testing.T.Errorf does not support %w (it's the same as fmt.Sprintf in what it does and doesn't accept), so the warnings are correct.

The messages do not stop your code from building and running, but in the case of an error, the formatting of the string will be off.

If you run the code, and there's an error, you'll get something like this (the part after %!w will depend on the exact error value you have).

Error on executing the test cases %!w(*errors.errorString=&{some error})

The specific warning you're getting might be new1, but I don't believe this error code would ever have worked satisfactorily in any version of go. Of course, since most test errors are most often not seen (because tests pass), it may be that this defect has remained invisible.

The fix is to replace %w (wrap error) with %v (format object in the default way, which for an error will be to use its string form).


1 The lint message you're seeing is from "go tool vet", created by this changelist which was committed in May 2021. It's possible on your other machine, you are linting using an earlier version of this tool.

  • Related