Skip to content

Commit

Permalink
Allow use of custom error messages with ErrorCodeInvalidParams. (#7)
Browse files Browse the repository at this point in the history
* Allow use of custom error messages with `ErrorCodeInvalidParams`.

* Add explicit test for custom `ErrorCodeInvalidParams` error messages.
  • Loading branch information
jmalloc committed May 19, 2020
1 parent 314a45a commit 0fb8d99
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
8 changes: 5 additions & 3 deletions methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,10 @@ func (method MethodFunc) call(ctx context.Context,
// InvalidParamsCode is the only reserved ErrorCode
// MethodFuncs are allowed to return.
if methodErr.Code == ErrorCodeInvalidParams {
// Ensure the correct message is used.
methodErr.Message = ErrorMessageInvalidParams
if methodErr.Message == "" {
// Ensure the correct message is used if none is supplied.
methodErr.Message = ErrorMessageInvalidParams
}
} else if methodErr.Code.IsReserved() {
panic(fmt.Errorf("invalid use of %v", methodErr.Code))
}
Expand Down Expand Up @@ -153,7 +155,7 @@ func (method MethodFunc) call(ctx context.Context,
// that here.
data, err := json.Marshal(result)
if err != nil {
panic(fmt.Sprintf("json.Marshal(result): %w", err))
panic(fmt.Errorf("json.Marshal(result): %w", err))
}
res.Result = json.RawMessage(data)
return
Expand Down
24 changes: 24 additions & 0 deletions methods_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,28 @@ func TestMethodFuncCall(t *testing.T) {
}
assert.Nil(res.Result)
assert.Empty(string(buf.Bytes()))

// Ensure the default error message is used for ErrorCodeInvalidParams, even
// if the implementation does not provide a message.
f = func(_ context.Context, _ json.RawMessage) interface{} {
return NewError(ErrorCodeInvalidParams, "", "data")
}
res = f.call(context.Background(), "", nil, lgr)
if assert.NotNil(res.Error) {
e := ErrorInvalidParams(json.RawMessage(`"data"`))
assert.Equal(e, res.Error)
}
assert.Nil(res.Result)
assert.Empty(string(buf.Bytes()))

// Ensure a custom error message is retained for ErrorCodeInvalidParams.
f = func(_ context.Context, _ json.RawMessage) interface{} {
return NewError(ErrorCodeInvalidParams, "a custom error message", "data")
}
res = f.call(context.Background(), "", nil, lgr)
if assert.NotNil(res.Error) {
assert.Equal("a custom error message", res.Error.Message)
}
assert.Nil(res.Result)
assert.Empty(string(buf.Bytes()))
}

0 comments on commit 0fb8d99

Please sign in to comment.