Skip to content

Commit fd499a0

Browse files
authored
Merge pull request #13 from RedMapleTech/feature/7-non-validation-errors-are-swallowed
Add detail for non-validation errors
2 parents db95c91 + cb46f2a commit fd499a0

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

bind/bind.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ type bindOpts struct {
3434
key string // Context key
3535
abort bool // Abort request on a bind error and set ctx.Error
3636
response bool // Abort request and send response immediately
37-
detail bool // Send validation error detail as JSON in response
37+
detail bool // Send error detail as JSON in response
3838
code int // HTTP status code if sending a response
3939
}
4040

@@ -108,8 +108,14 @@ func bindHandler(ctx *gin.Context, target interface{}, opts *bindOpts) {
108108
"errors": errs,
109109
}
110110
ctx.AbortWithStatusJSON(opts.code, res)
111+
} else if opts.detail {
112+
// Not a validation error but detail still requested
113+
ctx.AbortWithStatusJSON(opts.code, gin.H{
114+
"code": "binding_error",
115+
"error": err.Error(),
116+
})
111117
} else {
112-
// Error other than validation error
118+
// Error other than validation error or detail response disabled
113119
ctx.AbortWithStatus(opts.code)
114120
}
115121
return

bind/bind_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"io"
77
"net/http"
88
"net/http/httptest"
9+
"strings"
910
"testing"
1011

1112
"github.com/gin-gonic/gin"
@@ -193,6 +194,24 @@ func TestBindResponseDetail(t *testing.T) {
193194
assert.Equal(t, `{"code":"validation_error","errors":[{"field":"ID","rule":"uuid4"}]}`, w.Body.String())
194195
}
195196

197+
func TestBindResponseDetailNotValidation(t *testing.T) {
198+
type validatedBody struct {
199+
ID string `json:"id" binding:"required,uuid4"`
200+
}
201+
202+
w := httptest.NewRecorder()
203+
e := gin.New()
204+
205+
e.POST("", To(validatedBody{}, WithDetail(true)))
206+
207+
req, _ := http.NewRequest("POST", "/", strings.NewReader(`{"id": "invalid_json`))
208+
req.Header.Set("Content-Type", "application/json")
209+
210+
e.ServeHTTP(w, req)
211+
assert.Equal(t, 400, w.Result().StatusCode)
212+
assert.Equal(t, `{"code":"binding_error","error":"unexpected EOF"}`, w.Body.String())
213+
}
214+
196215
func body(i interface{}) io.Reader {
197216
buf, _ := json.Marshal(i)
198217
return bytes.NewReader(buf)

0 commit comments

Comments
 (0)