diff --git a/struct_utils/json.go b/struct_utils/json.go new file mode 100644 index 0000000000000000000000000000000000000000..ee887f5dcb882a7251a8c40b5c24cfb3f9a53619 --- /dev/null +++ b/struct_utils/json.go @@ -0,0 +1,20 @@ +package struct_utils + +import ( + "encoding/json" + "fmt" +) + +// UnmarshalJSON performs a JSON unmarshalling, but on type mismatches it returns a more user friendly error. +// Used exactly the same as json.Unmarshal +func UnmarshalJSON(data []byte, val interface{}) error { + err := json.Unmarshal(data, &val) + if err != nil { + typeErr, ok := err.(*json.UnmarshalTypeError) + if ok { + return fmt.Errorf("invalid type received for field '%s': expected a value of type '%s', but received type '%s'", typeErr.Field, typeErr.Type.Name(), typeErr.Value) + } + } + + return err +}