mirror of
https://github.com/gin-gonic/gin.git
synced 2026-07-09 04:02:00 +08:00
fix: record recovered panic errors
This commit is contained in:
parent
d75fcd4c9a
commit
a635b3a882
@ -106,7 +106,12 @@ func secureRequestDump(r *http.Request) string {
|
|||||||
return strings.Join(lines, "\r\n")
|
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)
|
c.AbortWithStatus(http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -5,6 +5,7 @@
|
|||||||
package gin
|
package gin
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@ -152,6 +153,48 @@ func TestPanicWithAbortHandler(t *testing.T) {
|
|||||||
assert.NotContains(t, out, "panic recovered")
|
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) {
|
func TestCustomRecoveryWithWriter(t *testing.T) {
|
||||||
errBuffer := new(strings.Builder)
|
errBuffer := new(strings.Builder)
|
||||||
buffer := new(strings.Builder)
|
buffer := new(strings.Builder)
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user