|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package mw
-
- import (
- "net"
- "net/http"
- "net/http/httputil"
- "os"
- "runtime/debug"
- "strings"
-
- "github.com/gin-gonic/gin"
- "go.uber.org/zap"
- )
-
- func Recovery(logger *zap.Logger, 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, false)
- if brokenPipe {
- logger.Error(c.Request.URL.Path,
- zap.Any("error", err),
- zap.String("request", string(httpRequest)),
- )
-
- c.Error(err.(error))
- c.Abort()
- return
- }
-
- if stack {
- logger.Error("[Recovery from panic]",
- zap.Any("error", err),
- zap.String("request", string(httpRequest)),
- zap.String("stack", string(debug.Stack())),
- )
- } else {
- logger.Error("[Recovery from panic]",
- zap.Any("error", err),
- zap.String("request", string(httpRequest)),
- )
- }
- c.AbortWithStatus(http.StatusInternalServerError)
- }
- }()
- c.Next()
- }
- }
|