This commit is contained in:
oneao committed 2025-08-14 17:28:32 +08:00
1 parent d1b1aafc57
commit 0f1604c709
58 files changed
+15476 -25

No files matched your search

@@ -2,22 +2,26 @@ package middleware
import (
"base-framework/pkg/router"
"base-framework/pkg/utils/response"
"log"
"fmt"
"net/http"
)
// Error 全局业务错误处理中间件
func Error() router.HandlerFunc {
return func(c *router.Context) {
// 执行业务逻辑
c.Next()
c.Next() // 执行后续 Handler
// 统一处理错误
if errs := c.Errors(); len(errs) > 0 {
errs := c.Errors()
if len(errs) > 0 {
lastErr := errs[len(errs)-1]
log.Printf("[ERROR] %v", lastErr)
response.Error(c).Send()
// 打印错误信息和堆栈
fmt.Printf("[ERROR] %v\nStack trace:\n%s\n", lastErr.Error(), lastErr.StackTrace())
// 返回前端安全信息
c.JSON(http.StatusInternalServerError, map[string]interface{}{
"code": "FAIL",
"message": lastErr.Error(),
})
c.Abort()
}
}
@@ -0,0 +1,24 @@
package middleware
import (
"base-framework/pkg/router"
"base-framework/pkg/utils/response"
"log"
"runtime/debug"
)
func Recovery() router.HandlerFunc {
return func(c *router.Context) {
defer func() {
if err := recover(); err != nil {
// 打印 panic 信息和堆栈
log.Printf("[Recovery] panic recovered: %v\n%s", err, debug.Stack())
response.Error(c).Send()
}
}()
// 调用后续 handler
c.Next()
}
}