Files
MyClub/internal/middleware/recovery.go
T
Tomas Dvorak b9cea0cd77 dev day #79
2025-11-02 01:04:02 +01:00

44 lines
856 B
Go

package middleware
import (
"fmt"
"net/http"
"runtime/debug"
"fotbal-club/pkg/logger"
"github.com/gin-gonic/gin"
)
// CustomRecovery returns a middleware that recovers from panics and logs them
func CustomRecovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
// Get stack trace
stack := string(debug.Stack())
// Log the panic
requestID := GetRequestID(c)
logger.Error("Panic recovered",
"request_id", requestID,
"error", fmt.Sprintf("%v", err),
"stack", stack,
"path", c.Request.URL.Path,
"method", c.Request.Method,
)
// Return error response
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Internal server error",
"request_id": requestID,
})
c.Abort()
}
}()
c.Next()
}
}