Skip to content

Commit 1ccd0e1

Browse files
committed
chore(http): add panic mw for chi base router
1 parent 1dac8c5 commit 1ccd0e1

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

http/router.go

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,12 @@ func newBaseChiRouter(errorHandler platform.HTTPErrorHandler) chi.Router {
3333
bh := baseHandler{HTTPErrorHandler: errorHandler}
3434
router.NotFound(bh.notFound)
3535
router.MethodNotAllowed(bh.methodNotAllowed)
36-
router.Use(kithttp.SkipOptions)
37-
router.Use(middleware.StripSlashes)
38-
router.Use(kithttp.SetCORS)
36+
router.Use(
37+
panicMW(bh),
38+
kithttp.SkipOptions,
39+
middleware.StripSlashes,
40+
kithttp.SetCORS,
41+
)
3942
return router
4043
}
4144

@@ -85,6 +88,21 @@ func (h baseHandler) panic(w http.ResponseWriter, r *http.Request, rcv interface
8588
h.HandleHTTPError(ctx, pe, w)
8689
}
8790

91+
func panicMW(b baseHandler) func(http.Handler) http.Handler {
92+
return func(next http.Handler) http.Handler {
93+
fn := func(w http.ResponseWriter, r *http.Request) {
94+
defer func() {
95+
if err := recover(); err != nil {
96+
w.WriteHeader(http.StatusInternalServerError)
97+
b.panic(w, r, err)
98+
}
99+
}()
100+
next.ServeHTTP(w, r)
101+
}
102+
return http.HandlerFunc(fn)
103+
}
104+
}
105+
88106
var panicLogger *zap.Logger
89107
var panicLoggerOnce sync.Once
90108

0 commit comments

Comments
 (0)