@@ -2,6 +2,7 @@ package middleware
2
2
3
3
import (
4
4
"bytes"
5
+ "errors"
5
6
"fmt"
6
7
"net/http"
7
8
"net/http/httptest"
@@ -81,3 +82,55 @@ func TestRecoverWithConfig_LogLevel(t *testing.T) {
81
82
})
82
83
}
83
84
}
85
+
86
+ func TestRecoverWithConfig_LogErrorFunc (t * testing.T ) {
87
+ e := echo .New ()
88
+ e .Logger .SetLevel (log .DEBUG )
89
+
90
+ buf := new (bytes.Buffer )
91
+ e .Logger .SetOutput (buf )
92
+
93
+ req := httptest .NewRequest (http .MethodGet , "/" , nil )
94
+ rec := httptest .NewRecorder ()
95
+ c := e .NewContext (req , rec )
96
+
97
+ testError := errors .New ("test" )
98
+ config := DefaultRecoverConfig
99
+ config .LogErrorFunc = func (c echo.Context , err error , stack []byte ) error {
100
+ msg := fmt .Sprintf ("[PANIC RECOVER] %v %s\n " , err , stack )
101
+ if errors .Is (err , testError ) {
102
+ c .Logger ().Debug (msg )
103
+ } else {
104
+ c .Logger ().Error (msg )
105
+ }
106
+ return err
107
+ }
108
+
109
+ t .Run ("first branch case for LogErrorFunc" , func (t * testing.T ) {
110
+ buf .Reset ()
111
+ h := RecoverWithConfig (config )(echo .HandlerFunc (func (c echo.Context ) error {
112
+ panic (testError )
113
+ }))
114
+
115
+ h (c )
116
+ assert .Equal (t , http .StatusInternalServerError , rec .Code )
117
+
118
+ output := buf .String ()
119
+ assert .Contains (t , output , "PANIC RECOVER" )
120
+ assert .Contains (t , output , `"level":"DEBUG"` )
121
+ })
122
+
123
+ t .Run ("else branch case for LogErrorFunc" , func (t * testing.T ) {
124
+ buf .Reset ()
125
+ h := RecoverWithConfig (config )(echo .HandlerFunc (func (c echo.Context ) error {
126
+ panic ("other" )
127
+ }))
128
+
129
+ h (c )
130
+ assert .Equal (t , http .StatusInternalServerError , rec .Code )
131
+
132
+ output := buf .String ()
133
+ assert .Contains (t , output , "PANIC RECOVER" )
134
+ assert .Contains (t , output , `"level":"ERROR"` )
135
+ })
136
+ }
0 commit comments