Skip to content

Commit

Permalink
fix: MarshalJSON method name in error message
Browse files Browse the repository at this point in the history
  • Loading branch information
blgm committed Jan 13, 2021
1 parent 3de60c7 commit a571e0c
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
7 changes: 4 additions & 3 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,16 +133,17 @@ func marshalMap(ctx context.Context, in reflect.Value) (out map[string]interface
}

func marshalJSONMarshaler(ctx context.Context, in reflect.Value) (interface{}, error) {
t := in.MethodByName("MarshalJSON").Call(nil)
const method = "MarshalJSON"
t := in.MethodByName(method).Call(nil)

if err := checkForError(t[1]); err != nil {
return nil, fmt.Errorf("error from MarshaJSON() call at %s: %w", ctx, err)
return nil, fmt.Errorf("error from %s() call at %s: %w", method, ctx, err)
}

var r interface{}
err := json.Unmarshal(t[0].Bytes(), &r)
if err != nil {
return nil, fmt.Errorf(`error parsing MarshaJSON() output "%s" at %s: %w`, t[0].Bytes(), ctx, err)
return nil, fmt.Errorf(`error parsing %s() output "%s" at %s: %w`, method, t[0].Bytes(), ctx, err)
}

return r, nil
Expand Down
4 changes: 2 additions & 2 deletions marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,8 @@ var _ = Describe("Marshal", func() {
expectToMarshal(struct{ I *implementsJSONMarshaler }{I: &implementsJSONMarshaler{bytes: []byte(`"hello"`)}}, `{"I":"hello"}`)
expectToMarshal(struct{ I *implementsJSONMarshaler }{I: (*implementsJSONMarshaler)(nil)}, `{"I":null}`)

expectToFail(struct{ I implementsJSONMarshaler }{I: implementsJSONMarshaler{err: errors.New("ouch")}}, `error from MarshaJSON() call at field "I" (type "jsonry_test.implementsJSONMarshaler"): ouch`)
expectToFail(struct{ I implementsJSONMarshaler }{I: implementsJSONMarshaler{}}, `error parsing MarshaJSON() output "" at field "I" (type "jsonry_test.implementsJSONMarshaler"): unexpected end of JSON input`)
expectToFail(struct{ I implementsJSONMarshaler }{I: implementsJSONMarshaler{err: errors.New("ouch")}}, `error from MarshalJSON() call at field "I" (type "jsonry_test.implementsJSONMarshaler"): ouch`)
expectToFail(struct{ I implementsJSONMarshaler }{I: implementsJSONMarshaler{}}, `error parsing MarshalJSON() output "" at field "I" (type "jsonry_test.implementsJSONMarshaler"): unexpected end of JSON input`)
})

It("marshals from named types and type aliases", func() {
Expand Down

0 comments on commit a571e0c

Please sign in to comment.