From edff2f198a2222f5b812a961aa5541e14aba7888 Mon Sep 17 00:00:00 2001 From: black1552 Date: Tue, 3 Feb 2026 16:40:50 +0800 Subject: [PATCH] =?UTF-8?q?fix(middleware):=20=E4=BF=AE=E5=A4=8Dpanic?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 统一错误响应结构,使用response.Error进行处理 - 添加字符串类型错误的处理分支 - 为未知错误类型设置默认错误消息 - 确保所有panic情况都会调用End方法结束响应 - 保持原有日志记录功能 --- middleware/middleware.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/middleware/middleware.go b/middleware/middleware.go index f59c788..1cc724d 100644 --- a/middleware/middleware.go +++ b/middleware/middleware.go @@ -12,12 +12,16 @@ func ErrorHandler() gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { + res := response.Error(c).SetCode(http.StatusInternalServerError) switch e := err.(type) { + case string: + res = res.SetMsg(e) case error: - response.Error(c).SetCode(http.StatusInternalServerError).SetMsg(e.Error()) + res = res.SetMsg(e.Error()) default: - log.Error(c.Errors.Last().Error()) + res = res.SetMsg("服务器内部异常,请稍后重试") } + res.End() log.Error("发生panic=》", "path:", c.Request.URL.Path, ",method:", c.Request.Method, ",", err) c.Abort() }