Skip to content

Commit

Permalink
Add type information to unmarshaling error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
oschwald committed Sep 20, 2023
1 parent affa445 commit e970a48
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
6 changes: 3 additions & 3 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ func (d *decoder) unmarshalMap(
result = indirect(result)
switch result.Kind() {
default:
return 0, newUnmarshalTypeError("map", result.Type())
return 0, newUnmarshalTypeStrError("map", result.Type())
case reflect.Struct:
return d.decodeStruct(size, offset, result, depth)
case reflect.Map:
Expand All @@ -430,7 +430,7 @@ func (d *decoder) unmarshalMap(
result.Set(rv)
return newOffset, err
}
return 0, newUnmarshalTypeError("map", result.Type())
return 0, newUnmarshalTypeStrError("map", result.Type())
}
}

Expand Down Expand Up @@ -465,7 +465,7 @@ func (d *decoder) unmarshalSlice(
return newOffset, err
}
}
return 0, newUnmarshalTypeError("array", result.Type())
return 0, newUnmarshalTypeStrError("array", result.Type())
}

func (d *decoder) unmarshalString(size, offset uint, result reflect.Value) (uint, error) {
Expand Down
10 changes: 7 additions & 3 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,17 @@ type UnmarshalTypeError struct {
Value string
}

func newUnmarshalTypeError(value any, rType reflect.Type) UnmarshalTypeError {
func newUnmarshalTypeStrError(value string, rType reflect.Type) UnmarshalTypeError {
return UnmarshalTypeError{
Value: fmt.Sprintf("%v", value),
Type: rType,
Value: value,
}
}

func newUnmarshalTypeError(value any, rType reflect.Type) UnmarshalTypeError {
return newUnmarshalTypeStrError(fmt.Sprintf("%v (%T)", value, value), rType)
}

func (e UnmarshalTypeError) Error() string {
return fmt.Sprintf("maxminddb: cannot unmarshal %s into type %s", e.Value, e.Type.String())
return fmt.Sprintf("maxminddb: cannot unmarshal %s into type %s", e.Value, e.Type)
}

0 comments on commit e970a48

Please sign in to comment.