From aae63769a1fc2af4f9c448923865e8d3fabe18f1 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Sat, 9 May 2020 01:38:00 +0900 Subject: [PATCH] Support MarshalerError --- README.md | 2 +- encode_test.go | 15 +++++++++++++++ encode_vm.go | 10 ++++++++-- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index afadb23..0522cdd 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ WIP - [ ] `InvalidUTF8Error` - [x] `InvalidUnmarshalError` -- [ ] `MarshalerError` +- [x] `MarshalerError` - [ ] `SyntaxError` - [ ] `UnmarshalFieldError` - [ ] `UnmarshalTypeError` diff --git a/encode_test.go b/encode_test.go index 48e2b8e..8e53205 100644 --- a/encode_test.go +++ b/encode_test.go @@ -1,6 +1,8 @@ package json_test import ( + "errors" + "fmt" "testing" "time" @@ -299,3 +301,16 @@ func Test_MarshalIndent(t *testing.T) { }) }) } + +type marshalerError struct{} + +func (*marshalerError) MarshalJSON() ([]byte, error) { + return nil, errors.New("unexpected error") +} + +func Test_MarshalerError(t *testing.T) { + var v marshalerError + _, err := json.Marshal(&v) + expect := `json: error calling MarshalJSON for type *json_test.marshalerError: unexpected error` + assertEq(t, "marshaler error", expect, fmt.Sprint(err)) +} diff --git a/encode_vm.go b/encode_vm.go index f2235ea..7ee3802 100644 --- a/encode_vm.go +++ b/encode_vm.go @@ -92,7 +92,10 @@ func (e *Encoder) run(code *opcode) error { })) bytes, err := v.(Marshaler).MarshalJSON() if err != nil { - return err + return &MarshalerError{ + Type: rtype2type(code.typ), + Err: err, + } } e.encodeBytes(bytes) code = code.next @@ -105,7 +108,10 @@ func (e *Encoder) run(code *opcode) error { })) bytes, err := v.(encoding.TextMarshaler).MarshalText() if err != nil { - return err + return &MarshalerError{ + Type: rtype2type(code.typ), + Err: err, + } } e.encodeBytes(bytes) code = code.next