github.com/hanks177/podman/v4@v4.1.3-0.20220613032544-16d90015bc83/pkg/api/server/handler_panic.go (about) 1 package server 2 3 import ( 4 "fmt" 5 "net/http" 6 "runtime" 7 8 "github.com/hanks177/podman/v4/pkg/api/handlers/utils" 9 "github.com/gorilla/mux" 10 "github.com/sirupsen/logrus" 11 ) 12 13 // panicHandler captures panics from endpoint handlers and logs stack trace 14 func panicHandler() mux.MiddlewareFunc { 15 return func(h http.Handler) http.Handler { 16 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 17 // http.Server hides panics from handlers, we want to record them and fix the cause 18 defer func() { 19 err := recover() 20 if err != nil { 21 buf := make([]byte, 1<<20) 22 n := runtime.Stack(buf, true) 23 logrus.Warnf("Recovering from API service endpoint handler panic: %v, %s", err, buf[:n]) 24 // Try to inform client things went south... won't work if handler already started writing response body 25 utils.InternalServerError(w, fmt.Errorf("%v", err)) 26 } 27 }() 28 29 h.ServeHTTP(w, r) 30 }) 31 } 32 }