golib/middleware/recover_log.go
2023-06-15 21:22:51 +08:00

55 lines
1.3 KiB
Go

//
// recover_log.go
// Copyright (C) 2022 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package middleware
import (
"net"
"net/http"
"net/http/httputil"
"os"
"strings"
"github.com/gin-gonic/gin"
"hexq.cn/tiglog/golib/logger"
)
func GinRecover() gin.HandlerFunc {
var log = logger.Recover()
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
// Check for a broken connection, as it is not really a
// condition that warrants a panic stack trace.
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 {
log.Error().Err(err.(error)).Str("request", string(httpRequest)).Msg(c.Request.URL.Path)
// If the connection is dead, we can't write a status to it.
c.Error(err.(error)) // nolint: errcheck
c.Abort()
return
}
var er = err.(error)
log.Error().Stack().Str("request", string(httpRequest)).Err(er).Msg("Recovery from panic")
c.AbortWithError(http.StatusInternalServerError, er)
}
}()
c.Next()
}
}