go

linter err113: do not define dynamic errors, use wrapped static errors instead


I am using err113 as part of golangci-lint.

It is complaining about ...

foo_test.go:55:61: err113: do not define dynamic errors, use wrapped static errors instead: "errors.New(\"repo gave err\")" (goerr113)
        repoMock.EXPECT().Save(gomock.Eq(&foooBarBar)).Return(nil, errors.New("repo gave err")),
                                                                  ^

foo_test.go:22:42: err113: do not define dynamic errors, use wrapped static errors instead: "errors.New(\"oops\")" (goerr113)
    repoMock.EXPECT().FindAll().Return(nil, errors.New("oops"))
                                            ^

What is best way to fix this ?

Quoting https://github.com/Djarvur/go-err113

Also, any call of errors.New() and fmt.Errorf() methods are reported except the calls used to initialise package-level variables and the fmt.Errorf() calls wrapping the other errors.

I am trying to get a idiomatic example for this.


Solution

  • Declare a package-level variables as suggested:

     var repoGaveErr = errors.New("repo gave err")
    
     func someFunc() {
        repoMock.EXPECT().Save(gomock.Eq(&foooBarBar)).Return(nil, repoGaveErr)
     }
    

    Every call to errors.New allocates a new unique error value. The application creates a single value representing the error by declaring the package-level variable.

    There are two motivations for the single value:

    The value io.EOF is a canonical example.