You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
crate/bunrouterhelper/middleware.go

49 lines
1.2 KiB
Go

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
}
}
}