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)
| 20 | // |
| 21 | // Alternatively, look at https://github.com/go-chi/httplog middleware pkgs. |
| 22 | func 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 |
| 52 | var recovererErrorWriter io.Writer = os.Stderr |
nothing calls this directly
no test coverage detected