32 lines
725 B
Go
32 lines
725 B
Go
package middleware
|
|
|
|
import (
|
|
"base-go-v2/internal/logx"
|
|
response "base-go-v2/internal/reponse"
|
|
"base-go-v2/internal/router"
|
|
"runtime/debug"
|
|
)
|
|
|
|
func RecoveryMiddleware() router.HandlerFunc {
|
|
return func(c *router.Context) error {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
stack := string(debug.Stack()) // 获取堆栈
|
|
|
|
logx.Logger.Error("请求 panic",
|
|
logx.String("path", string(c.RequestCtx.Path())),
|
|
logx.String("method", string(c.RequestCtx.Method())),
|
|
logx.String("panic", r.(error).Error()),
|
|
logx.String("stack", stack),
|
|
)
|
|
|
|
// 返回统一 JSON 响应
|
|
_ = response.Error(c).Message("系统 Panic").Send()
|
|
}
|
|
}()
|
|
|
|
// 调用后续 handler
|
|
return c.Next()
|
|
}
|
|
}
|