From 0e753522722e892a9f87298fbed2501d4f238f28 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Fri, 20 Oct 2023 13:08:52 +0200 Subject: [PATCH] HMS-2837 fix: middleware validation error response 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 --- .../infrastructure/middleware/validate_api.go | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/internal/infrastructure/middleware/validate_api.go b/internal/infrastructure/middleware/validate_api.go index 60d61a2f..a839f0b9 100644 --- a/internal/infrastructure/middleware/validate_api.go +++ b/internal/infrastructure/middleware/validate_api.go @@ -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()) } } @@ -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, @@ -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)