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

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 application can compare values for equality to check for a specific error condition.

  • Reduce memory allocations (although probably not a big deal in practice)

The value io.EOF is a canonical example.


Since GO 1.13 you can define a new error type, wrap it and use it. for example, if you want to return an "operation not permitted" + the operation. you need to implement something like

var OperationNotPermit = errors.New("operation not permitted")

func OperationNotFoundError(op string) error {
    return fmt.Errorf("OperationNotPermit %w : %s", OperationNotPermit, op)
}

then in your code, when you want to return the error,

return nil, OperationNotFoundError(Op)

Let's back to question case:

first, define the custom error and the wapper

var repoError = errors.New("repositoryError")

func RepositoryError(msg string) error {
    return fmt.Errorf("%w: %s", repoError,msg)
}

then in your code,

repoMock.EXPECT().Save(gomock.Eq(&foooBarBar)).Return(nil, RepositoryError("YOUR CUSTOM ERROR MESSAGE"))

Tags:

Go