Commit
This commit is contained in:
55
middleware/gin_recovery.go
Normal file
55
middleware/gin_recovery.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"nCovTrack-Backend/utils"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func GinRecovery(stack bool) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
var brokenPipe bool
|
||||
if ne, ok := err.(*net.OpError); ok {
|
||||
if se, ok := ne.Err.(*os.SyscallError); ok {
|
||||
if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
|
||||
brokenPipe = true
|
||||
}
|
||||
}
|
||||
}
|
||||
httpRequest, _ := httputil.DumpRequest(c.Request, true)
|
||||
var logParams []interface{}
|
||||
logParams = append(logParams,
|
||||
"uri", c.Request.RequestURI,
|
||||
"method", c.Request.Method,
|
||||
"request", string(httpRequest),
|
||||
"error", interface{}(err),
|
||||
)
|
||||
if brokenPipe {
|
||||
utils.RequestLogPanic(logParams...)
|
||||
c.Error(err.(error))
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
logParams = append(logParams,
|
||||
"status", "recovery from panic",
|
||||
)
|
||||
if stack {
|
||||
logParams = append(logParams,
|
||||
"stack", string(debug.Stack()),
|
||||
)
|
||||
}
|
||||
utils.RequestLogPanic(logParams...)
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user