golib/middleware/recover_log.go

58 lines
1.4 KiB
Go
Raw Normal View History

2023-06-15 21:22:51 +08:00
//
// 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"
2023-07-15 17:52:50 +08:00
"git.hexq.cn/tiglog/golib/helper"
2023-06-15 21:38:12 +08:00
"git.hexq.cn/tiglog/golib/logger"
2023-07-15 17:52:50 +08:00
"github.com/gin-gonic/gin"
2023-06-15 21:22:51 +08:00
)
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 {
2023-07-15 17:52:50 +08:00
log.Error().Err(err.(error)).Str("request", string(httpRequest)).
Msg(c.Request.URL.Path)
2023-06-15 21:22:51 +08:00
// 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)
2023-07-15 17:52:50 +08:00
log.Error().Str("request", string(httpRequest)).
Err(helper.WrapErr(er, "wrap")).Msg("Recovery from panic")
2023-06-15 21:22:51 +08:00
c.AbortWithError(http.StatusInternalServerError, er)
}
}()
c.Next()
}
}