Files
go-sms-V2/internal/middleware/recovery.go
T

42 lines
1.1 KiB
Go

package middleware
import (
"net/http"
"runtime/debug"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"go-sms/internal/pkg/errors"
)
// Recovery 全局异常恢复中间件(Day 15,替代 gin.Recovery):
// 捕获 panic → 记录堆栈与请求上下文(含 trace_id)→ 返回
// 500 {"code":"ISC:500","msg":"系统内部错误"},进程不崩溃。
func Recovery(lg *zap.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
fields := []zap.Field{
zap.Any("panic", r),
zap.String("stack", string(debug.Stack())),
zap.String("method", c.Request.Method),
zap.String("path", c.Request.URL.Path),
zap.Int("status_pending", c.Writer.Status()),
}
if v, ok := c.Get(TraceIDKey); ok {
if id, ok := v.(string); ok {
fields = append(fields, zap.String("trace_id", id))
}
}
lg.Error("panic_recovered", fields...)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"code": errors.InternalError.Code,
"msg": errors.InternalError.Msg,
})
}
}()
c.Next()
}
}