Files
nCovTrack-Backend/middleware/gin_recovery.go
fallen-angle 2d43931fc8 feat: add jwt
2022-02-10 17:08:42 +08:00

76 lines
1.6 KiB
Go

package middleware
import (
"fmt"
"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.RequestLogError(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.RequestLogError(logParams...)
c.AbortWithStatus(http.StatusInternalServerError)
fmt.Printf("\n%s\n", err)
fmt.Printf("\n%s\n", cutStack(debug.Stack()))
}
}()
c.Next()
}
}
func cutStack(stack []byte) string {
stackStr := string(stack)
line := 0
lastLineCharIndex := 0
for index, char := range stackStr {
if char == '\n' {
line++
}
if line == 7 {
lastLineCharIndex = index + 1
break
}
}
fmt.Println(stackStr[lastLineCharIndex:])
return ""
}