MCPcopy
hub / github.com/go-chi/chi / Recoverer

Function Recoverer

middleware/recoverer.go:22–49  ·  view source on GitHub ↗

Recoverer is a middleware that recovers from panics, logs the panic (and a backtrace), and returns a HTTP 500 (Internal Server Error) status if possible. Recoverer prints a request ID if one is provided. Alternatively, look at https://github.com/go-chi/httplog middleware pkgs.

(next http.Handler)

Source from the content-addressed store, hash-verified

20//
21// Alternatively, look at https://github.com/go-chi/httplog middleware pkgs.
22func Recoverer(next http.Handler) http.Handler {
23 fn := func(w http.ResponseWriter, r *http.Request) {
24 defer func() {
25 if rvr := recover(); rvr != nil {
26 if rvr == http.ErrAbortHandler {
27 // we don't recover http.ErrAbortHandler so the response
28 // to the client is aborted, this should not be logged
29 panic(rvr)
30 }
31
32 logEntry := GetLogEntry(r)
33 if logEntry != nil {
34 logEntry.Panic(rvr, debug.Stack())
35 } else {
36 PrintPrettyStack(rvr)
37 }
38
39 if r.Header.Get("Connection") != "Upgrade" {
40 w.WriteHeader(http.StatusInternalServerError)
41 }
42 }
43 }()
44
45 next.ServeHTTP(w, r)
46 }
47
48 return http.HandlerFunc(fn)
49}
50
51// for ability to test the PrintPrettyStack function
52var recovererErrorWriter io.Writer = os.Stderr

Callers

nothing calls this directly

Calls 7

GetLogEntryFunction · 0.85
PrintPrettyStackFunction · 0.85
HandlerFuncMethod · 0.80
PanicMethod · 0.65
GetMethod · 0.65
WriteHeaderMethod · 0.45
ServeHTTPMethod · 0.45

Tested by

no test coverage detected