Regression test for #2771: a BindingError returned from a handler must be serialized by DefaultHTTPErrorHandler into a structured response that retains the field name (and the binder message), not flattened to {"message":"Bad Request"}.
(t *testing.T)
| 16 | // serialized by DefaultHTTPErrorHandler into a structured response that retains |
| 17 | // the field name (and the binder message), not flattened to {"message":"Bad Request"}. |
| 18 | func TestBindingError_serializesToStructuredJSON(t *testing.T) { |
| 19 | e := New() |
| 20 | e.GET("/doc", func(c *Context) error { |
| 21 | var docNum int |
| 22 | return QueryParamsBinder(c).MustInt("docNum", &docNum).BindError() |
| 23 | }) |
| 24 | |
| 25 | req := httptest.NewRequest(http.MethodGet, "/doc?docNum=abc", nil) |
| 26 | rec := httptest.NewRecorder() |
| 27 | e.ServeHTTP(rec, req) |
| 28 | |
| 29 | assert.Equal(t, http.StatusBadRequest, rec.Code) |
| 30 | |
| 31 | var body map[string]any |
| 32 | assert.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) |
| 33 | assert.Equal(t, "docNum", body["field"], "binding error response must retain the field name") |
| 34 | assert.Equal(t, "failed to bind field value to int", body["message"], "binding error response must retain the binder message") |
| 35 | } |
| 36 | |
| 37 | // When the binding error carries no message, MarshalJSON falls back to the |
| 38 | // status text (mirroring DefaultHTTPErrorHandler's *HTTPError branch). |