package mw import ( "net/http" "runtime/debug" "code.nochebuena.dev/einherjar/contracts/logging" ) // Recover catches panics in downstream handlers, writes a 500 response, and // logs the recovered value with a stack trace. Place it as the outermost middleware. func Recover(logger logging.Logger) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if rec := recover(); rec != nil { logger.WithContext(r.Context()).Error("recover: panic", nil, "panic", rec, "stack", string(debug.Stack()), ) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } }() next.ServeHTTP(w, r) }) } }