Skip to content

Commit

Permalink
Recover middleware should not log panic for aborted handler (#2134, f…
Browse files Browse the repository at this point in the history
…ixes #2133)

Co-authored-by: Becir Basic <bb@neotel.at>
  • Loading branch information
bbasic and Becir Basic committed Mar 15, 2022
1 parent 05df10c commit 5c38c3b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
4 changes: 4 additions & 0 deletions middleware/recover.go
Expand Up @@ -2,6 +2,7 @@ package middleware

import (
"fmt"
"net/http"
"runtime"

"github.com/labstack/echo/v4"
Expand Down Expand Up @@ -77,6 +78,9 @@ func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc {

defer func() {
if r := recover(); r != nil {
if r == http.ErrAbortHandler {
panic(r)
}
err, ok := r.(error)
if !ok {
err = fmt.Errorf("%v", r)
Expand Down
29 changes: 29 additions & 0 deletions middleware/recover_test.go
Expand Up @@ -28,6 +28,35 @@ func TestRecover(t *testing.T) {
assert.Contains(t, buf.String(), "PANIC RECOVER")
}

func TestRecoverErrAbortHandler(t *testing.T) {
e := echo.New()
buf := new(bytes.Buffer)
e.Logger.SetOutput(buf)
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
h := Recover()(echo.HandlerFunc(func(c echo.Context) error {
panic(http.ErrAbortHandler)
}))
defer func() {
r := recover()
if r == nil {
assert.Fail(t, "expecting `http.ErrAbortHandler`, got `nil`")
} else {
if err, ok := r.(error); ok {
assert.ErrorIs(t, err, http.ErrAbortHandler)
} else {
assert.Fail(t, "not of error type")
}
}
}()

h(c)

assert.Equal(t, http.StatusInternalServerError, rec.Code)
assert.NotContains(t, buf.String(), "PANIC RECOVER")
}

func TestRecoverWithConfig_LogLevel(t *testing.T) {
tests := []struct {
logLevel log.Lvl
Expand Down

0 comments on commit 5c38c3b

Please sign in to comment.