Add options, mostly transformers

This commit is contained in:
Dan Jones 2024-01-21 21:40:06 -06:00
commit b4b4f041d7
4 changed files with 121 additions and 11 deletions

View file

@ -7,7 +7,16 @@ import (
"github.com/gin-gonic/gin"
)
func ErrorMiddleware() gin.HandlerFunc {
func ErrorMiddleware(opts ...Option) gin.HandlerFunc {
conf := config{}
for _, opt := range opts {
conf = opt(conf)
}
if len(conf.transformers) == 0 {
conf.transformers = []Transformer{ginTransformer}
}
return func(c *gin.Context) {
c.Next()
err := c.Errors.Last()
@ -16,24 +25,27 @@ func ErrorMiddleware() gin.HandlerFunc {
}
var re rErrors.ResponsableError
errors.As(err, &re)
// If we have at least one that's a ResponsableError, we should use it
for _, err = range c.Errors {
errors.As(err, &re)
if re != nil {
break
}
errors.As(err, &re)
}
// @todo we need to add some way to do custom handling
// @todo Refactor this with 👆
if re == nil {
switch err.Type {
case gin.ErrorTypePrivate:
re = rErrors.NewInternalError("%w", err)
default:
re = rErrors.NewBadRequest("%w", err)
// Next, let's check our transformers
for _, trans := range conf.transformers {
if re != nil {
break
}
re = trans(err)
}
// Still couldn't find one, so it's a 500
if re == nil {
re = rErrors.NewInternalError("%w", err)
}
c.JSON(re.Status(), re)