diff --git a/recovery.go b/recovery.go index 2124fe5f..8bfb5783 100644 --- a/recovery.go +++ b/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() diff --git a/recovery_test.go b/recovery_test.go index e5211790..e9a999d7 100644 --- a/recovery_test.go +++ b/recovery_test.go @@ -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")