Fix error handler

The errors can not be of the type validation error, for example if the
json string cannot be parsed.
This commit is contained in:
Jannis Mattheis 2018-02-11 22:38:46 +01:00 committed by Jannis Mattheis
parent edec140c82
commit 74d80765e5
2 changed files with 18 additions and 1 deletions

View File

@ -27,7 +27,13 @@ func Handler() gin.HandlerFunc {
for _, e := range c.Errors { for _, e := range c.Errors {
switch e.Type { switch e.Type {
case gin.ErrorTypeBind: case gin.ErrorTypeBind:
errs := e.Err.(validator.ValidationErrors) errs, ok := e.Err.(validator.ValidationErrors)
if !ok {
writeError(c, e.Error())
return
}
var stringErrors []string var stringErrors []string
for _, err := range errs { for _, err := range errs {
stringErrors = append(stringErrors, validationErrorToText(err)) stringErrors = append(stringErrors, validationErrorToText(err))

View File

@ -22,6 +22,17 @@ func TestDefaultErrorInternal(t *testing.T) {
assertJSONResponse(t, rec, 500, `{"errorCode":500, "errorDescription":"something went wrong", "error":"Internal Server Error"}`) assertJSONResponse(t, rec, 500, `{"errorCode":500, "errorDescription":"something went wrong", "error":"Internal Server Error"}`)
} }
func TestBindingErrorDefault(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.AbortWithError(400, errors.New("you need todo something")).SetType(gin.ErrorTypeBind)
Handler()(ctx)
assertJSONResponse(t, rec, 400, `{"errorCode":400, "errorDescription":"you need todo something", "error":"Bad Request"}`)
}
func TestDefaultErrorBadRequest(t *testing.T) { func TestDefaultErrorBadRequest(t *testing.T) {
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()