-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrecoverer.go
51 lines (42 loc) · 1.38 KB
/
recoverer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright (c) Liam Stanley <[email protected]>. All rights reserved. Use of
// this source code is governed by the MIT license that can be found in
// the LICENSE file.
package chix
import (
"fmt"
"net/http"
"runtime/debug"
"github.com/go-chi/chi/v5/middleware"
)
// Deprecated: Recoverer is deprecated, and will be removed in a future release.
// Please use UseRecoverer instead.
func Recoverer(next http.Handler) http.Handler {
return UseRecoverer(next)
}
// UseRecoverer is a middleware that recovers from panics, and returns a chix.Error
// with HTTP 500 status (Internal Server Error) if possible. If debug is enabled,
// through UseDebug(), a stack trace will be printed to stderr, otherwise to
// standard structured logging.
//
// NOTE: This middleware should be loaded after logging/request-id/use-debug, etc
// middleware, but before the handlers that may panic.
func UseRecoverer(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rvr := recover(); rvr != nil {
if rvr == http.ErrAbortHandler {
panic(rvr)
}
err := fmt.Errorf("panic recovered: %v", rvr)
if IsDebug(r) {
middleware.PrintPrettyStack(rvr)
} else {
Log(r).WithError(err).Error(string(debug.Stack()))
}
ErrorCode(w, r, http.StatusInternalServerError, err)
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}