From d36ff729613dd8e825455c504bea0586c43ac03d Mon Sep 17 00:00:00 2001 From: AnuchitO Date: Tue, 1 May 2018 16:18:55 +0700 Subject: [PATCH] Add field name in Error message when Binding type mismatch Old error message ` Unmarshal type error: expected=int, got=string, offset=47 ` New error message ` Unmarshal type error: expected=int, got=string, field=age, offset=47 ` Make it easy to fix for client. --- bind.go | 2 +- bind_test.go | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/bind.go b/bind.go index 38e07150..04aa8125 100644 --- a/bind.go +++ b/bind.go @@ -44,7 +44,7 @@ func (b *DefaultBinder) Bind(i interface{}, c Context) (err error) { case strings.HasPrefix(ctype, MIMEApplicationJSON): if err = json.NewDecoder(req.Body).Decode(i); err != nil { if ute, ok := err.(*json.UnmarshalTypeError); ok { - return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, offset=%v", ute.Type, ute.Value, ute.Offset)) + return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, field=%v, offset=%v", ute.Type, ute.Value, ute.Field, ute.Offset)) } else if se, ok := err.(*json.SyntaxError); ok { return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: offset=%v, error=%v", se.Offset, se.Error())) } else { diff --git a/bind_test.go b/bind_test.go index 2fe59573..8b12ebda 100644 --- a/bind_test.go +++ b/bind_test.go @@ -208,6 +208,23 @@ func TestBindbindData(t *testing.T) { assertBindTestStruct(t, ts) } +func TestBindUnmarshalTypeError(t *testing.T) { + body := bytes.NewBufferString(`{ "id": "text" }`) + e := New() + req := httptest.NewRequest(POST, "/", body) + req.Header.Set(HeaderContentType, MIMEApplicationJSON) + + rec := httptest.NewRecorder() + c := e.NewContext(req, rec) + u := new(user) + + err := c.Bind(u) + + he := &HTTPError{Code: http.StatusBadRequest, Message: "Unmarshal type error: expected=int, got=string, field=id, offset=14"} + + assert.Equal(t, he, err) +} + func TestBindSetWithProperType(t *testing.T) { ts := new(bindTestStruct) typ := reflect.TypeOf(ts).Elem()