diff --git a/decode.go b/decode.go index b30087fc..e91b32c2 100644 --- a/decode.go +++ b/decode.go @@ -207,11 +207,13 @@ func (e *DupMapKeyError) Error() string { // UnknownFieldError describes detected unknown field in CBOR map when decoding to Go struct. type UnknownFieldError struct { - Index int + Struct string // name of the struct being decoded + Field string // field of the CBOR map that was unexpected + Index int // index of the field in the CBOR map } func (e *UnknownFieldError) Error() string { - return fmt.Sprintf("cbor: found unknown field at map element index %d", e.Index) + return fmt.Sprintf("cbor: found unknown field: struct '%s' has no field '%s', at map element index %d", e.Struct, e.Field, e.Index) } // UnacceptableDataItemError is returned when unmarshaling a CBOR input that contains a data item @@ -2617,8 +2619,8 @@ MapEntryLoop: var k any t := d.nextCBORType() + var keyBytes []byte if t == cborTypeTextString || (t == cborTypeByteString && d.dm.fieldNameByteString == FieldNameByteStringAllowed) { - var keyBytes []byte if t == cborTypeTextString { keyBytes, lastErr = d.parseTextString() if lastErr != nil { @@ -2767,7 +2769,7 @@ MapEntryLoop: if f == nil { if errOnUnknownField { - err = &UnknownFieldError{j} + err = &UnknownFieldError{Struct: tInfo.typ.String(), Field: string(keyBytes), Index: j} d.skip() // Skip value j++ // skip the rest of the map diff --git a/decode_test.go b/decode_test.go index 5880d73a..171d3f41 100644 --- a/decode_test.go +++ b/decode_test.go @@ -6825,7 +6825,7 @@ func TestExtraErrorCondUnknownField(t *testing.T) { name: "CBOR map unknown field with ExtraDecErrorUnknownField", data: hexDecode("a461416161614261626143616361446164"), // map[string]string{"A": "a", "B": "b", "C": "c", "D": "d"} dm: dmUnknownFieldError, - wantErrorMsg: "cbor: found unknown field at map element index 3", + wantErrorMsg: "cbor: found unknown field: struct 'cbor.s' has no field 'D', at map element index 3", }, } for _, tc := range testCases { @@ -6885,7 +6885,7 @@ func TestStreamExtraErrorCondUnknownField(t *testing.T) { } data := hexDecode("a461416161614461646142616261436163a3614161616142616261436163") // map[string]string{"A": "a", "D": "d", "B": "b", "C": "c"}, map[string]string{"A": "a", "B": "b", "C": "c"} - wantErrorMsg := "cbor: found unknown field at map element index 1" + wantErrorMsg := "cbor: found unknown field: struct 'cbor.s' has no field 'D', at map element index 1" wantObj := s{A: "a", B: "b", C: "c"} dmUnknownFieldError, _ := DecOptions{ExtraReturnErrors: ExtraDecErrorUnknownField}.DecMode()