From 3bc489254b96e24a3f8d0d723a0a755e729744ee Mon Sep 17 00:00:00 2001 From: hkfires <10558748+hkfires@users.noreply.github.com> Date: Mon, 15 Dec 2025 16:36:01 +0800 Subject: [PATCH] fix(api): prevent double logging for error responses The WriteErrorResponse function now caches the error response body in the gin context. The deferred request logger checks for this cached response. If an error response is found, it bypasses the standard response logging. This prevents scenarios where an error is logged twice or an empty payload log overwrites the original, more detailed error log. --- sdk/api/handlers/handlers.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/sdk/api/handlers/handlers.go b/sdk/api/handlers/handlers.go index 14ba83ce..a17e54aa 100644 --- a/sdk/api/handlers/handlers.go +++ b/sdk/api/handlers/handlers.go @@ -118,6 +118,16 @@ func (h *BaseAPIHandler) GetContextWithCancel(handler interfaces.APIHandler, c * newCtx = context.WithValue(newCtx, "handler", handler) return newCtx, func(params ...interface{}) { if h.Cfg.RequestLog && len(params) == 1 { + if existing, exists := c.Get("API_RESPONSE"); exists { + if existingBytes, ok := existing.([]byte); ok && len(bytes.TrimSpace(existingBytes)) > 0 { + switch params[0].(type) { + case error, string: + cancel() + return + } + } + } + var payload []byte switch data := params[0].(type) { case []byte: @@ -477,11 +487,14 @@ func (h *BaseAPIHandler) WriteErrorResponse(c *gin.Context, msg *interfaces.Erro return payload } + body := buildJSONBody() + c.Set("API_RESPONSE", bytes.Clone(body)) + if !c.Writer.Written() { c.Writer.Header().Set("Content-Type", "application/json") } c.Status(status) - _, _ = c.Writer.Write(buildJSONBody()) + _, _ = c.Writer.Write(body) } func (h *BaseAPIHandler) LoggingAPIResponseError(ctx context.Context, err *interfaces.ErrorMessage) {