Fix not being able to return UnmarshalTypeError when it should be returned

This commit is contained in:
Masaaki Goshima 2021-02-18 11:32:08 +09:00
parent b0e53330b6
commit b2a7d22fb4
3 changed files with 16 additions and 4 deletions

View File

@ -214,7 +214,7 @@ func (d *interfaceDecoder) decodeStream(s *stream, p unsafe.Pointer) error {
if u, ok := rv.Interface().(encoding.TextUnmarshaler); ok {
return decodeStreamTextUnmarshaler(s, u, p)
}
return &UnsupportedTypeError{Type: rv.Type()}
return d.errUnmarshalType(rv.Type(), s.totalOffset())
}
iface := rv.Interface()
ifaceHeader := (*interfaceHeader)(unsafe.Pointer(&iface))
@ -241,6 +241,16 @@ func (d *interfaceDecoder) decodeStream(s *stream, p unsafe.Pointer) error {
return decoder.decodeStream(s, ifaceHeader.ptr)
}
func (d *interfaceDecoder) errUnmarshalType(typ reflect.Type, offset int64) *UnmarshalTypeError {
return &UnmarshalTypeError{
Value: typ.String(),
Type: typ,
Offset: offset,
Struct: d.structName,
Field: d.fieldName,
}
}
func (d *interfaceDecoder) decode(buf []byte, cursor int64, p unsafe.Pointer) (int64, error) {
runtimeInterfaceValue := *(*interface{})(unsafe.Pointer(&interfaceHeader{
typ: d.typ,
@ -254,7 +264,7 @@ func (d *interfaceDecoder) decode(buf []byte, cursor int64, p unsafe.Pointer) (i
if u, ok := rv.Interface().(encoding.TextUnmarshaler); ok {
return decodeTextUnmarshaler(buf, cursor, u, p)
}
return 0, &UnsupportedTypeError{Type: rv.Type()}
return 0, d.errUnmarshalType(rv.Type(), cursor)
}
iface := rv.Interface()

View File

@ -231,6 +231,8 @@ func (d *stringDecoder) decodeStreamByte(s *stream) ([]byte, error) {
continue
case '[':
return nil, d.errUnmarshalType("array", s.totalOffset())
case '{':
return nil, d.errUnmarshalType("object", s.totalOffset())
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
return nil, d.errUnmarshalType("number", s.totalOffset())
case '"':
@ -257,6 +259,8 @@ func (d *stringDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, err
cursor++
case '[':
return nil, 0, d.errUnmarshalType("array", cursor)
case '{':
return nil, 0, d.errUnmarshalType("object", cursor)
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
return nil, 0, d.errUnmarshalType("number", cursor)
case '"':

View File

@ -2317,7 +2317,6 @@ var decodeTypeErrorTests = []struct {
{new(error), `true`},
}
/*
func TestUnmarshalTypeError(t *testing.T) {
for _, item := range decodeTypeErrorTests {
err := json.Unmarshal([]byte(item.src), item.dest)
@ -2327,7 +2326,6 @@ func TestUnmarshalTypeError(t *testing.T) {
}
}
}
*/
var unmarshalSyntaxTests = []string{
"tru",