gocommon/ginutils/recovery.go
Matthieu 'JP' DERASSE 959f245c01
All checks were successful
continuous-integration/drone/push Build is passing
feat(ginutils): Add ginutils that is a toolbox for gin gonic
2023-08-11 18:39:40 +00:00

49 lines
1.1 KiB
Go

package ginutils
import (
"fmt"
"runtime/debug"
"strings"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// Recovery will catch a panic and :
// - Recover
// - log the stacktrace.
func Recovery(handler gin.HandlerFunc) gin.HandlerFunc {
if handler == nil {
handler = func(c *gin.Context) {
c.AbortWithStatusJSON(500, map[string]string{
"message": "Internal Server Error",
"debugId": c.GetString(string(ContextKey_RequestID)),
})
}
}
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
// log the error
log := GetLoggerWithFields(c, logrus.Fields{
"error": err,
"stacktrace": fmt.Sprintf("%v\n%s", err, getStacktrace()),
})
if log != nil {
log.Error("A Panic happened and has been caught")
}
handler(c)
}
}()
c.Next()
gin.Recovery()
}
}
func getStacktrace() string {
stackLines := strings.Split(string(debug.Stack()), "\n")
// removing a few first line as they are either that function or the middleware
return strings.Join(stackLines[9:], "\n")
}