From 3bfca3805aaa4c1f7673c7dd3b834b942f752788 Mon Sep 17 00:00:00 2001 From: black1552 Date: Tue, 3 Feb 2026 16:25:36 +0800 Subject: [PATCH] =?UTF-8?q?fix(middleware):=20=E4=BF=AE=E5=A4=8Dpanic?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=E4=B8=AD=E7=9A=84=E9=94=99=E8=AF=AF=E5=A4=84?= =?UTF-8?q?=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 当发生panic时检查上下文错误列表 - 使用最后一个错误作为响应内容 - 移除直接使用panic值的逻辑 - 改进错误消息的安全性,避免敏感信息泄露 - 确保在panic情况下正确终止请求处理 --- middleware/middleware.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/middleware/middleware.go b/middleware/middleware.go index 0cc9ab2..6e1ad15 100644 --- a/middleware/middleware.go +++ b/middleware/middleware.go @@ -12,8 +12,14 @@ func ErrorHandler() gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { + if len(c.Errors) > 0 { + // Step3: Use the last error + laErr := c.Errors.Last().Err + + // Step4: Respond with a generic error message + response.Error(c).SetCode(http.StatusInternalServerError).SetMsg(laErr.Error()).End() + } log.Error("发生panic=》", "path:", c.Request.URL.Path, ",method:", c.Request.Method, ",", err) - response.Error(c).SetCode(http.StatusInternalServerError).SetMsg(err.(error).Error()).End() c.Abort() } }()