Skip to content

Commit

Permalink
Added a optional config variable to disable centralized error handler…
Browse files Browse the repository at this point in the history
… in recovery middleware (#2410)

Added a config variable to disable centralized error handler in recovery middleware
  • Loading branch information
Omkar-C authored Feb 24, 2023
1 parent 47844c9 commit 1e575b7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
15 changes: 13 additions & 2 deletions middleware/recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ type (
// LogErrorFunc defines a function for custom logging in the middleware.
// If it's set you don't need to provide LogLevel for config.
LogErrorFunc LogErrorFunc

// DisableErrorHandler disables the call to centralized HTTPErrorHandler.
// The recovered error is then passed back to upstream middleware, instead of swallowing the error.
// Optional. Default value false.
DisableErrorHandler bool `yaml:"disable_error_handler"`
}
)

Expand All @@ -50,6 +55,7 @@ var (
DisablePrintStack: false,
LogLevel: 0,
LogErrorFunc: nil,
DisableErrorHandler: false,
}
)

Expand All @@ -71,7 +77,7 @@ func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc {
}

return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return func(c echo.Context) (returnErr error) {
if config.Skipper(c) {
return next(c)
}
Expand Down Expand Up @@ -113,7 +119,12 @@ func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc {
c.Logger().Print(msg)
}
}
c.Error(err)

if(!config.DisableErrorHandler) {
c.Error(err)
} else {
returnErr = err
}
}
}()
return next(c)
Expand Down
23 changes: 22 additions & 1 deletion middleware/recover_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ func TestRecover(t *testing.T) {
h := Recover()(echo.HandlerFunc(func(c echo.Context) error {
panic("test")
}))
h(c)
err := h(c)
assert.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, rec.Code)
assert.Contains(t, buf.String(), "PANIC RECOVER")
}
Expand Down Expand Up @@ -163,3 +164,23 @@ func TestRecoverWithConfig_LogErrorFunc(t *testing.T) {
assert.Contains(t, output, `"level":"ERROR"`)
})
}

func TestRecoverWithDisabled_ErrorHandler(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)

config := DefaultRecoverConfig
config.DisableErrorHandler = true
h := RecoverWithConfig(config)(echo.HandlerFunc(func(c echo.Context) error {
panic("test")
}))
err := h(c)

assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, buf.String(), "PANIC RECOVER")
assert.EqualError(t, err, "test")
}

0 comments on commit 1e575b7

Please sign in to comment.