Skip to content

Commit

Permalink
HMS-2837 fix: middleware validation error response
Browse files Browse the repository at this point in the history
We should not return a plaintext error response as the error won't be displayed
in this case. By returning a new HTTP error the default error handler of the
echo server will take care of it creating the error response in the correct
format. As this is a REST API, the error will be returned in json format.

Pair-Programmed-With: Alejandro Visiedo <[email protected]>
  • Loading branch information
cryptomilk committed Oct 25, 2023
1 parent d5ab3bb commit 0e75352
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions internal/infrastructure/middleware/validate_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,7 @@ func RequestResponseValidatorWithConfig(config *RequestResponseValidatorConfig)
requestValidationInput,
)
if err != nil {
c.Response().Header().Set(echo.HeaderContentType, "text/plain")
c.String(http.StatusBadRequest, err.Error())
return nil // stop processing
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
}

Expand All @@ -273,6 +271,12 @@ func RequestResponseValidatorWithConfig(config *RequestResponseValidatorConfig)
c.Response().Writer = resRec

defer func() {
// reset the response, using the original ResponseWriter
c.SetResponse(echo.NewResponse(rw, c.Echo()))
}()

err = next(c)
if err == nil {
responseValidationInput := &openapi3filter.ResponseValidationInput{
RequestValidationInput: requestValidationInput,
Status: resRec.status,
Expand All @@ -285,19 +289,15 @@ func RequestResponseValidatorWithConfig(config *RequestResponseValidatorConfig)
responseValidationInput,
); err != nil {
// write error response
c.Response().Header().Set(echo.HeaderContentType, "text/plain")
c.String(http.StatusInternalServerError, err.Error())
} else {
// Write original response
rw.WriteHeader(resRec.status)
resRec.buffer.WriteTo(rw)
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
}()

defer func() {
// reset the response, using the original ResponseWriter
c.SetResponse(echo.NewResponse(rw, c.Echo()))
}()
// Write original response
rw.WriteHeader(resRec.status)
resRec.buffer.WriteTo(rw)
}

return err
}

return next(c)
Expand Down

0 comments on commit 0e75352

Please sign in to comment.