Some checks failed
CI/CD Pipeline / Test (push) Failing after 22m19s
CI/CD Pipeline / Security Scan (push) Failing after 5m57s
CI/CD Pipeline / Build (amd64, darwin) (push) Has been skipped
CI/CD Pipeline / Build (amd64, linux) (push) Has been skipped
CI/CD Pipeline / Build (amd64, windows) (push) Has been skipped
CI/CD Pipeline / Build (arm64, darwin) (push) Has been skipped
CI/CD Pipeline / Build (arm64, linux) (push) Has been skipped
CI/CD Pipeline / Build Docker Image (push) Has been skipped
CI/CD Pipeline / Create Release (push) Has been skipped
36 lines
885 B
Go
36 lines
885 B
Go
package middleware
|
||
|
||
import (
|
||
"fmt"
|
||
|
||
"github.com/gofiber/fiber/v2"
|
||
"github.com/subconverter-go/internal/logging"
|
||
)
|
||
|
||
// SetupRecovery 设置恢复中间件
|
||
// 捕获panic并记录错误日志,返回友好的错误响应
|
||
func SetupRecovery(logger *logging.Logger) fiber.Handler {
|
||
return func(c *fiber.Ctx) error {
|
||
defer func() {
|
||
if r := recover(); r != nil {
|
||
// 记录panic日志
|
||
logger.WithFields(map[string]interface{}{
|
||
"method": c.Method(),
|
||
"path": c.Path(),
|
||
"ip": c.IP(),
|
||
"user_agent": c.Get("User-Agent"),
|
||
"panic": fmt.Sprintf("%v", r),
|
||
}).Error("Recovered from panic")
|
||
|
||
// 返回错误响应
|
||
c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||
"success": false,
|
||
"error": "Internal server error",
|
||
"message": "An unexpected error occurred",
|
||
})
|
||
}
|
||
}()
|
||
|
||
return c.Next()
|
||
}
|
||
} |