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`
- [x] `InvalidUnmarshalError`
- [ ] `MarshalerError`
- [x] `MarshalerError`
- [ ] `SyntaxError`
- [ ] `UnmarshalFieldError`
- [ ] `UnmarshalTypeError`

View File

@ -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))
}

View File

@ -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