diff --git a/context_test.go b/context_test.go
index 9ce16e37..c65738c2 100644
--- a/context_test.go
+++ b/context_test.go
@@ -34,6 +34,7 @@ func TestContext(t *testing.T) {
userJSONIndent := "{\n_?\"id\": \"1\",\n_?\"name\": \"Joe\"\n_}"
userXML := `1Joe`
userXMLIndent := "_\n_?1\n_?Joe\n_"
+ incorrectContent := "this is incorrect content"
var nonMarshallableChannel chan bool
@@ -68,14 +69,18 @@ func TestContext(t *testing.T) {
//------
// JSON
- testBind(t, c, "application/json")
+ testBindOk(t, c, ApplicationJSON)
+ c.request, _ = http.NewRequest(POST, "/", strings.NewReader(incorrectContent))
+ testBindError(t, c, ApplicationJSON)
// XML
c.request, _ = http.NewRequest(POST, "/", strings.NewReader(userXML))
- testBind(t, c, ApplicationXML)
+ testBindOk(t, c, ApplicationXML)
+ c.request, _ = http.NewRequest(POST, "/", strings.NewReader(incorrectContent))
+ testBindError(t, c, ApplicationXML)
// Unsupported
- testBind(t, c, "")
+ testBindError(t, c, "")
//--------
// Render
@@ -291,14 +296,30 @@ func TestContextEcho(t *testing.T) {
assert.Nil(t, c.Echo())
}
-func testBind(t *testing.T, c *Context, ct string) {
+func testBindOk(t *testing.T, c *Context, ct string) {
c.request.Header.Set(ContentType, ct)
u := new(user)
err := c.Bind(u)
- if ct == "" {
- assert.Error(t, ErrUnsupportedMediaType)
- } else if assert.NoError(t, err) {
+ if assert.NoError(t, err) {
assert.Equal(t, "1", u.ID)
assert.Equal(t, "Joe", u.Name)
}
}
+
+func testBindError(t *testing.T, c *Context, ct string) {
+ c.request.Header.Set(ContentType, ct)
+ u := new(user)
+ err := c.Bind(u)
+
+ switch ct {
+ case ApplicationJSON, ApplicationXML:
+ if assert.IsType(t, new(HTTPError), err) {
+ assert.Equal(t, http.StatusBadRequest, err.(*HTTPError).code)
+ }
+ default:
+ if assert.IsType(t, new(HTTPError), err) {
+ assert.Equal(t, ErrUnsupportedMediaType, err)
+ }
+
+ }
+}
diff --git a/echo.go b/echo.go
index 1f21863b..6859bab5 100644
--- a/echo.go
+++ b/echo.go
@@ -204,7 +204,7 @@ var (
// Errors
//--------
- ErrUnsupportedMediaType = errors.New("unsupported media type")
+ ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType)
ErrRendererNotRegistered = errors.New("renderer not registered")
ErrInvalidRedirectCode = errors.New("invalid redirect status code")
@@ -734,9 +734,14 @@ func (binder) Bind(r *http.Request, i interface{}) (err error) {
ct := r.Header.Get(ContentType)
err = ErrUnsupportedMediaType
if strings.HasPrefix(ct, ApplicationJSON) {
- err = json.NewDecoder(r.Body).Decode(i)
+ if err = json.NewDecoder(r.Body).Decode(i); err != nil {
+ err = NewHTTPError(http.StatusBadRequest, err.Error())
+ }
} else if strings.HasPrefix(ct, ApplicationXML) {
- err = xml.NewDecoder(r.Body).Decode(i)
+ if err = xml.NewDecoder(r.Body).Decode(i); err != nil {
+ err = NewHTTPError(http.StatusBadRequest, err.Error())
+ }
+
}
return
}