1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00

Fix #1794: panics in timeout middleware are not recovered and cause application to crash

This commit is contained in:
toimtoimtoim 2021-03-01 23:45:18 +02:00 committed by Martti T
parent c79ffed7ce
commit b2444d8399
2 changed files with 31 additions and 0 deletions

View File

@ -4,6 +4,7 @@ package middleware
import (
"context"
"fmt"
"github.com/labstack/echo/v4"
"time"
)
@ -62,6 +63,17 @@ func TimeoutWithConfig(config TimeoutConfig) echo.MiddlewareFunc {
done := make(chan error, 1)
go func() {
defer func() {
if r := recover(); r != nil {
err, ok := r.(error)
if !ok {
err = fmt.Errorf("panic recovered in timeout middleware: %v", r)
}
c.Logger().Error(err)
done <- err
}
}()
// This goroutine will keep running even if this middleware times out and
// will be stopped when ctx.Done() is called down the next(c) call chain
done <- next(c)

View File

@ -175,3 +175,22 @@ func TestTimeoutTestRequestClone(t *testing.T) {
assert.NoError(t, err)
}
func TestTimeoutRecoversPanic(t *testing.T) {
t.Parallel()
m := TimeoutWithConfig(TimeoutConfig{
Timeout: 25 * time.Millisecond,
})
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
e := echo.New()
c := e.NewContext(req, rec)
err := m(func(c echo.Context) error {
panic("panic in handler")
})(c)
assert.Error(t, err, "panic recovered in timeout middleware: panic in handler")
}