Files
ginframework/http/recovery/recovery.go
T
2026-11-28 02:51:21 -08:00

56 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package recovery 捕获 Gin 请求 panic,允许应用显式提供报告和响应协议。
package recovery
import (
"fmt"
"net/http"
"runtime/debug"
"git.zhangdeman.cn/zhangdeman/ginframework/fault"
"git.zhangdeman.cn/zhangdeman/ginframework/logger"
"github.com/gin-gonic/gin"
)
const codePanic = 900901
// Incident 只包含 panic 类型和单次采集的调用栈,不保存原始 panic 值。
type Incident struct {
Type string `json:"type" dc:"panic 动态类型,不调用其格式化方法"`
Stack []byte `json:"-" dc:"本次恢复的单次调用栈,仅供内部诊断"`
}
// Options 指定 panic 的诊断和安全响应边界。
type Options struct {
Report func(*gin.Context, Incident) `json:"-" dc:"同步记录一次 panic,nil 使用框架安全错误日志"`
Respond func(*gin.Context) `json:"-" dc:"未提交响应时调用的安全响应函数,nil 返回通用 JSON 500"`
}
// New 创建 panic 恢复中间件;入参为应用协议回调,返回 Gin Handler。
// 仅恢复当前请求协程,不吞掉普通 error;报告后中止处理链。
// 响应已提交(包括 SSE Flush)时不追加 JSON 或改写状态,仍报告并 Abort。
// 不拥有日志资源;应用负责回调的并发安全和不泄漏诊断内容。
func New(options Options) gin.HandlerFunc {
return func(ctx *gin.Context) {
defer func() {
if recovered := recover(); recovered != nil {
incident := Incident{Type: fmt.Sprintf("%T", recovered), Stack: debug.Stack()}
ctx.Abort()
if options.Report != nil {
options.Report(ctx, incident)
} else {
logger.RecordErrorContext(ctx.Request.Context(), "recover HTTP handler panic", fault.New(codePanic, "recover HTTP handler panic", nil))
}
if ctx.Writer.Written() {
return
}
if options.Respond != nil {
options.Respond(ctx)
} else {
ctx.JSON(http.StatusInternalServerError, gin.H{"code": http.StatusInternalServerError, "message": "Internal Server Error"})
}
}
}()
ctx.Next()
}
}