package bunrouterhelper import ( "errors" "fmt" "net/http" "git.blauwelle.com/go/crate/httpdata" "git.blauwelle.com/go/crate/log" "github.com/uptrace/bunrouter" ) func MiddlewareRecover() bunrouter.MiddlewareFunc { return func(next bunrouter.HandlerFunc) bunrouter.HandlerFunc { return func(w http.ResponseWriter, req bunrouter.Request) (err error) { defer func() { if r := recover(); r != nil { log.Error(req.Context(), r) err = httpdata.NewUniverseError(httpdata.CodeUnexpectPanic, fmt.Sprintf("%v", r)) } }() return next(w, req) } } } func MiddlewareErrorHandler() bunrouter.MiddlewareFunc { return func(next bunrouter.HandlerFunc) bunrouter.HandlerFunc { return func(w http.ResponseWriter, req bunrouter.Request) error { err := next(w, req) if err != nil { var universeError httpdata.UniverseError if errors.As(err, &universeError) { _ = bunrouter.JSON(w, httpdata.Response{ Code: universeError.Code, Message: universeError.Message, }) } else { _ = bunrouter.JSON(w, httpdata.Response{ Code: httpdata.CodeUnknown, Message: err.Error(), }) } } return err } } }