Skip to content

Commit 1e575b7

Browse files
authored
Added a optional config variable to disable centralized error handler in recovery middleware (#2410)
Added a config variable to disable centralized error handler in recovery middleware
1 parent 47844c9 commit 1e575b7

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

middleware/recover.go

+13-2
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ type (
3838
// LogErrorFunc defines a function for custom logging in the middleware.
3939
// If it's set you don't need to provide LogLevel for config.
4040
LogErrorFunc LogErrorFunc
41+
42+
// DisableErrorHandler disables the call to centralized HTTPErrorHandler.
43+
// The recovered error is then passed back to upstream middleware, instead of swallowing the error.
44+
// Optional. Default value false.
45+
DisableErrorHandler bool `yaml:"disable_error_handler"`
4146
}
4247
)
4348

@@ -50,6 +55,7 @@ var (
5055
DisablePrintStack: false,
5156
LogLevel: 0,
5257
LogErrorFunc: nil,
58+
DisableErrorHandler: false,
5359
}
5460
)
5561

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

7379
return func(next echo.HandlerFunc) echo.HandlerFunc {
74-
return func(c echo.Context) error {
80+
return func(c echo.Context) (returnErr error) {
7581
if config.Skipper(c) {
7682
return next(c)
7783
}
@@ -113,7 +119,12 @@ func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc {
113119
c.Logger().Print(msg)
114120
}
115121
}
116-
c.Error(err)
122+
123+
if(!config.DisableErrorHandler) {
124+
c.Error(err)
125+
} else {
126+
returnErr = err
127+
}
117128
}
118129
}()
119130
return next(c)

middleware/recover_test.go

+22-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ func TestRecover(t *testing.T) {
2323
h := Recover()(echo.HandlerFunc(func(c echo.Context) error {
2424
panic("test")
2525
}))
26-
h(c)
26+
err := h(c)
27+
assert.NoError(t, err)
2728
assert.Equal(t, http.StatusInternalServerError, rec.Code)
2829
assert.Contains(t, buf.String(), "PANIC RECOVER")
2930
}
@@ -163,3 +164,23 @@ func TestRecoverWithConfig_LogErrorFunc(t *testing.T) {
163164
assert.Contains(t, output, `"level":"ERROR"`)
164165
})
165166
}
167+
168+
func TestRecoverWithDisabled_ErrorHandler(t *testing.T) {
169+
e := echo.New()
170+
buf := new(bytes.Buffer)
171+
e.Logger.SetOutput(buf)
172+
req := httptest.NewRequest(http.MethodGet, "/", nil)
173+
rec := httptest.NewRecorder()
174+
c := e.NewContext(req, rec)
175+
176+
config := DefaultRecoverConfig
177+
config.DisableErrorHandler = true
178+
h := RecoverWithConfig(config)(echo.HandlerFunc(func(c echo.Context) error {
179+
panic("test")
180+
}))
181+
err := h(c)
182+
183+
assert.Equal(t, http.StatusOK, rec.Code)
184+
assert.Contains(t, buf.String(), "PANIC RECOVER")
185+
assert.EqualError(t, err, "test")
186+
}

0 commit comments

Comments
 (0)