mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-02-20 21:30:50 +08:00
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.
This commit is contained in:
@@ -118,6 +118,16 @@ func (h *BaseAPIHandler) GetContextWithCancel(handler interfaces.APIHandler, c *
|
|||||||
newCtx = context.WithValue(newCtx, "handler", handler)
|
newCtx = context.WithValue(newCtx, "handler", handler)
|
||||||
return newCtx, func(params ...interface{}) {
|
return newCtx, func(params ...interface{}) {
|
||||||
if h.Cfg.RequestLog && len(params) == 1 {
|
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
|
var payload []byte
|
||||||
switch data := params[0].(type) {
|
switch data := params[0].(type) {
|
||||||
case []byte:
|
case []byte:
|
||||||
@@ -477,11 +487,14 @@ func (h *BaseAPIHandler) WriteErrorResponse(c *gin.Context, msg *interfaces.Erro
|
|||||||
return payload
|
return payload
|
||||||
}
|
}
|
||||||
|
|
||||||
|
body := buildJSONBody()
|
||||||
|
c.Set("API_RESPONSE", bytes.Clone(body))
|
||||||
|
|
||||||
if !c.Writer.Written() {
|
if !c.Writer.Written() {
|
||||||
c.Writer.Header().Set("Content-Type", "application/json")
|
c.Writer.Header().Set("Content-Type", "application/json")
|
||||||
}
|
}
|
||||||
c.Status(status)
|
c.Status(status)
|
||||||
_, _ = c.Writer.Write(buildJSONBody())
|
_, _ = c.Writer.Write(body)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *BaseAPIHandler) LoggingAPIResponseError(ctx context.Context, err *interfaces.ErrorMessage) {
|
func (h *BaseAPIHandler) LoggingAPIResponseError(ctx context.Context, err *interfaces.ErrorMessage) {
|
||||||
|
|||||||
Reference in New Issue
Block a user