fix: record recovered panic errors

This commit is contained in:
m0_66095053 2026-06-09 14:07:36 +08:00
parent d75fcd4c9a
commit a635b3a882
2 changed files with 49 additions and 1 deletions

View File

@ -106,7 +106,12 @@ func secureRequestDump(r *http.Request) string {
return strings.Join(lines, "\r\n")
}
func defaultHandleRecovery(c *Context, _ any) {
func defaultHandleRecovery(c *Context, err any) {
if e, ok := err.(error); ok {
c.Error(e) //nolint: errcheck
} else {
c.Error(fmt.Errorf("%v", err)) //nolint: errcheck
}
c.AbortWithStatus(http.StatusInternalServerError)
}

View File

@ -5,6 +5,7 @@
package gin
import (
"errors"
"net"
"net/http"
"os"
@ -152,6 +153,48 @@ func TestPanicWithAbortHandler(t *testing.T) {
assert.NotContains(t, out, "panic recovered")
}
func TestPanicInHandlerRecordsError(t *testing.T) {
tests := []struct {
name string
recoveredErr any
expectedErr string
}{
{
name: "string panic",
recoveredErr: "Oops, Houston, we have a problem",
expectedErr: "Oops, Houston, we have a problem",
},
{
name: "error panic",
recoveredErr: errors.New("recovered error"),
expectedErr: "recovered error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
router := New()
var recoveredErrors errorMsgs
router.Use(func(c *Context) {
c.Next()
recoveredErrors = c.Errors
})
router.Use(RecoveryWithWriter(nil))
router.GET("/recovery", func(_ *Context) {
panic(tt.recoveredErr)
})
w := PerformRequest(router, http.MethodGet, "/recovery")
assert.Equal(t, http.StatusInternalServerError, w.Code)
if assert.Len(t, recoveredErrors, 1) {
assert.EqualError(t, recoveredErrors[0], tt.expectedErr)
}
})
}
}
func TestCustomRecoveryWithWriter(t *testing.T) {
errBuffer := new(strings.Builder)
buffer := new(strings.Builder)