41 lines
1.0 KiB
Go
41 lines
1.0 KiB
Go
package middleware
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
"runtime/debug"
|
|
|
|
"git.coopcloud.tech/wiki-cafe/member-console/internal/logging"
|
|
)
|
|
|
|
// Recovery middleware catches panics and logs them with structured logging
|
|
func Recovery() Middleware {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
defer func() {
|
|
if err := recover(); err != nil {
|
|
// Get logger from context
|
|
logger := logging.FromContext(r.Context())
|
|
|
|
// Get request ID from context
|
|
requestID := GetRequestID(r.Context())
|
|
|
|
// Log the panic with stack trace
|
|
logger.Error("panic recovered",
|
|
slog.String("request_id", requestID),
|
|
slog.String("method", r.Method),
|
|
slog.String("path", r.URL.Path),
|
|
slog.Any("error", err),
|
|
slog.String("stack", string(debug.Stack())),
|
|
)
|
|
|
|
// Return 500 Internal Server Error to the client
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
}
|
|
}()
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|