mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-17 15:23:44 +08:00
Merge 8b7ef9abb558afbb27847e55635cebf63be2bf2c into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646
This commit is contained in:
commit
0ef0db3be4
17
recovery.go
17
recovery.go
@ -60,15 +60,18 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
|
||||
if rec := recover(); rec != nil {
|
||||
// Check for a broken connection, as it is not really a
|
||||
// condition that warrants a panic stack trace.
|
||||
var isBrokenPipe bool
|
||||
var (
|
||||
isBrokenPipe bool
|
||||
isAbortHandler bool
|
||||
)
|
||||
err, ok := rec.(error)
|
||||
if ok {
|
||||
isAbortHandler = errors.Is(err, http.ErrAbortHandler)
|
||||
isBrokenPipe = errors.Is(err, syscall.EPIPE) ||
|
||||
errors.Is(err, syscall.ECONNRESET) ||
|
||||
errors.Is(err, http.ErrAbortHandler)
|
||||
errors.Is(err, syscall.ECONNRESET)
|
||||
}
|
||||
if logger != nil {
|
||||
if isBrokenPipe {
|
||||
if isBrokenPipe || isAbortHandler {
|
||||
logger.Printf("%s\n%s%s", rec, secureRequestDump(c.Request), reset)
|
||||
} else if IsDebugging() {
|
||||
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
|
||||
@ -78,13 +81,17 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
|
||||
timeFormat(time.Now()), rec, stack(stackSkip), reset)
|
||||
}
|
||||
}
|
||||
if isBrokenPipe {
|
||||
if isBrokenPipe || isAbortHandler {
|
||||
// If the connection is dead, we can't write a status to it.
|
||||
c.Error(err) //nolint: errcheck
|
||||
c.Abort()
|
||||
} else {
|
||||
handle(c, rec)
|
||||
}
|
||||
// Re-panic error for http.Server to handle it properly.
|
||||
if isAbortHandler {
|
||||
panic(rec)
|
||||
}
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
|
||||
@ -6,14 +6,17 @@ package gin
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPanicClean(t *testing.T) {
|
||||
@ -141,13 +144,16 @@ func TestPanicWithAbortHandler(t *testing.T) {
|
||||
c.Header("X-Test", "Value")
|
||||
c.Status(expectCode)
|
||||
|
||||
// Panic with ErrAbortHandler which should be treated as broken pipe
|
||||
// Panic with ErrAbortHandler which should be treated as special
|
||||
panic(http.ErrAbortHandler)
|
||||
})
|
||||
// RUN
|
||||
w := PerformRequest(router, http.MethodGet, "/recovery")
|
||||
srv := httptest.NewServer(router)
|
||||
defer srv.Close()
|
||||
_, err := srv.Client().Get(srv.URL + "/recovery")
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, io.EOF)
|
||||
// TEST
|
||||
assert.Equal(t, expectCode, w.Code)
|
||||
out := buf.String()
|
||||
assert.Contains(t, out, "net/http: abort Handler")
|
||||
assert.NotContains(t, out, "panic recovered")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user