gocommon/ginutils/recovery.go
Matthieu 'JP' DERASSE 77b4351ef1
All checks were successful
continuous-integration/drone/push Build is passing
feat(error): Create api error. WIP
2023-08-22 19:59:44 +00:00

46 lines
1004 B
Go

package ginutils
import (
"fmt"
"runtime/debug"
"strings"
"git.dev.m-and-m.ovh/mderasse/gocommon/aerr"
"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) {
errorHandler(c, aerr.NewInternalServerError())
}
}
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()
}
}
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")
}