59 lines
1.3 KiB
Go
59 lines
1.3 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.Println(err)
|
|
fmt.Printf("\n%s\n", debug.Stack())
|
|
}
|
|
}()
|
|
c.Next()
|
|
}
|
|
}
|