forked from mtusi2026/mtusi2026lab6
33 lines
747 B
Go
33 lines
747 B
Go
package middleware
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
"runtime/debug"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
func Recover(logger *slog.Logger) echo.MiddlewareFunc {
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) (err error) {
|
|
defer func() {
|
|
r := recover()
|
|
if r == nil {
|
|
return
|
|
}
|
|
rid, _ := c.Get(RequestIDKey).(string)
|
|
logger.Error("panic recovered",
|
|
slog.String("request_id", rid),
|
|
slog.String("method", c.Request().Method),
|
|
slog.String("path", c.Request().URL.Path),
|
|
slog.Any("panic", r),
|
|
slog.String("stack", string(debug.Stack())),
|
|
)
|
|
err = echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
|
|
}()
|
|
return next(c)
|
|
}
|
|
}
|
|
}
|