forked from mirror/go-json
Support MarshalerError
This commit is contained in:
parent
3d786b69c4
commit
aae63769a1
|
@ -68,7 +68,7 @@ WIP
|
|||
|
||||
- [ ] `InvalidUTF8Error`
|
||||
- [x] `InvalidUnmarshalError`
|
||||
- [ ] `MarshalerError`
|
||||
- [x] `MarshalerError`
|
||||
- [ ] `SyntaxError`
|
||||
- [ ] `UnmarshalFieldError`
|
||||
- [ ] `UnmarshalTypeError`
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
|
|
10
encode_vm.go
10
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
|
||||
|
|
Loading…
Reference in New Issue