feat: add Recovery middleware for panic handling with verbose logging

This commit is contained in:
GitHub Actions
2025-11-30 22:19:38 +00:00
parent b2bcbe86bb
commit 48fbca2eee
2 changed files with 97 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
package middleware
import (
"log"
"net/http"
"runtime/debug"
"github.com/gin-gonic/gin"
)
// Recovery logs panic information. When verbose is true it logs stacktraces
// and basic request metadata for debugging.
func Recovery(verbose bool) gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
if verbose {
log.Printf("PANIC: %v\nRequest: %s %s\nHeaders: %v\nStacktrace:\n%s", r, c.Request.Method, c.Request.URL.String(), c.Request.Header, debug.Stack())
} else {
log.Printf("PANIC: %v", r)
}
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "internal server error"})
}
}()
c.Next()
}
}