Support MarshalerError

This commit is contained in:
Masaaki Goshima 2020-05-09 01:38:00 +09:00
parent 3d786b69c4
commit aae63769a1
3 changed files with 24 additions and 3 deletions

View File

@ -68,7 +68,7 @@ WIP
- [ ] `InvalidUTF8Error` - [ ] `InvalidUTF8Error`
- [x] `InvalidUnmarshalError` - [x] `InvalidUnmarshalError`
- [ ] `MarshalerError` - [x] `MarshalerError`
- [ ] `SyntaxError` - [ ] `SyntaxError`
- [ ] `UnmarshalFieldError` - [ ] `UnmarshalFieldError`
- [ ] `UnmarshalTypeError` - [ ] `UnmarshalTypeError`

View File

@ -1,6 +1,8 @@
package json_test package json_test
import ( import (
"errors"
"fmt"
"testing" "testing"
"time" "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))
}

View File

@ -92,7 +92,10 @@ func (e *Encoder) run(code *opcode) error {
})) }))
bytes, err := v.(Marshaler).MarshalJSON() bytes, err := v.(Marshaler).MarshalJSON()
if err != nil { if err != nil {
return err return &MarshalerError{
Type: rtype2type(code.typ),
Err: err,
}
} }
e.encodeBytes(bytes) e.encodeBytes(bytes)
code = code.next code = code.next
@ -105,7 +108,10 @@ func (e *Encoder) run(code *opcode) error {
})) }))
bytes, err := v.(encoding.TextMarshaler).MarshalText() bytes, err := v.(encoding.TextMarshaler).MarshalText()
if err != nil { if err != nil {
return err return &MarshalerError{
Type: rtype2type(code.typ),
Err: err,
}
} }
e.encodeBytes(bytes) e.encodeBytes(bytes)
code = code.next code = code.next