Files
workspace/code/go-project/base-farmework/pkg/middleware/error.go
T
2025-08-14 21:45:18 +08:00

68 lines
1.5 KiB
Go

package middleware
import (
"base-framework/pkg/reponse"
"strings"
"base-framework/pkg/router"
)
// Error 中间件:捕获 c.Errors() 并返回统一的 ErrorInfo
func Error() router.HandlerFunc {
return func(c *router.Context) {
c.Next() // 执行后续 Handler
errs := c.Errors()
if len(errs) == 0 {
return
}
lastErr := errs[len(errs)-1]
stack := lastErr.StackTrace()
location := extractBusinessLocation(stack)
info := reponse.ErrorInfo{
Method: c.Request.Method,
Path: c.Request.URL.Path,
Message: lastErr.Error(),
Stack: stack, // 完整堆栈
Location: location, // 业务 Handler 文件行号
}
reponse.Error(c).ErrorInfo(info).Send()
c.Abort()
}
}
// extractBusinessLocation:获取 AddError 后的业务 Handler 文件行号
func extractBusinessLocation(stack string) string {
lines := strings.Split(stack, "\n")
foundAddError := false
countGo := 0
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.Contains(line, "AddError") {
foundAddError = true
continue
}
if foundAddError && strings.Contains(line, ".go:") {
countGo++
if countGo == 2 { // 第2个 .go: 行就是业务 Handler
// 去掉 +0x偏移
if idx := strings.Index(line, " +"); idx != -1 {
line = line[:idx]
}
// 保留 base-farmework 开头的路径
slash := strings.Index(line, "base-farmework")
if slash != -1 {
line = line[slash:]
}
return line
}
}
}
return ""
}