| 1 | package zhttp |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "net/http" |
| 7 | "runtime" |
| 8 | "strings" |
| 9 | |
| 10 | "github.com/rs/zerolog" |
| 11 | ) |
| 12 | |
| 13 | // RecoveryMiddleware catches panics, logs the error, and writes a generic Internal Server Error response |
| 14 | func RecoveryMiddleware(next http.Handler) http.Handler { |
| 15 | return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { |
| 16 | defer func() { |
| 17 | if caught := recover(); caught != nil { |
| 18 | if caught == http.ErrAbortHandler { |
| 19 | // explicit signal to stop |
| 20 | panic(caught) |
| 21 | } |
| 22 | const size = 64 << 10 |
| 23 | buf := make([]byte, size) |
| 24 | buf = buf[:runtime.Stack(buf, false)] |
| 25 | tb := "\n " + strings.Replace(string(buf), "\n", "\n ", -1) |
| 26 | err, ok := caught.(error) |
| 27 | if !ok { |
| 28 | err = fmt.Errorf("%v", caught) |
| 29 | } |
| 30 | WriteUnhandledError(rw, req, err, tb) |
| 31 | } |
| 32 | }() |
| 33 | next.ServeHTTP(rw, req) |
| 34 | }) |
| 35 | } |
| 36 | |
| 37 | // WriteUnhandledError writes a generic 500 Internal Server Error response while |
| 38 | // logging the actual unhandled error and optional traceback |
| 39 | func WriteUnhandledError(w http.ResponseWriter, req *http.Request, err error, traceback string) { |
| 40 | status := http.StatusInternalServerError |
| 41 | field := "error" |
| 42 | text := "An unhandled exception occurred while processing your request. Please contact your administrator." |
| 43 | if e := req.Context().Err(); e != nil { |
| 44 | field = "cancel" |
| 45 | text = "" |
| 46 | if e == context.DeadlineExceeded { |
| 47 | status = http.StatusGatewayTimeout |
| 48 | } else { |
| 49 | // borrow nginx's fake 499 status for client closing connection |
| 50 | status = 499 |
| 51 | } |
| 52 | } |
| 53 | AppendAccessLog(req, func(e *zerolog.Event) { |
| 54 | e.AnErr(field, err) |
| 55 | if traceback != "" { |
| 56 | e.Str("stack", traceback) |
| 57 | } |
| 58 | }) |
| 59 | http.Error(w, text, status) |
| 60 | } |