package handler import ( "errors" rErrors "codeberg.org/danjones000/responsable-errors" "github.com/gin-gonic/gin" ) type config struct { loggers []LoggerFunc transformers []Transformer } // A function which should be used to log the responded error. type LoggerFunc func(*gin.Context, rErrors.ResponsableError) // A function which should potentially return a [rErrors.ResponsableError] which wraps the provided error. type Transformer func(error) rErrors.ResponsableError // An option that customizes the behavior of [ErrorMiddleware] type Option func(config) config // Provides an [Option] which adds the specified [LoggerFunc] to the [ErrorMiddleware] // // Multiple [LoggerFunc] may be added. func WithLogger(logger LoggerFunc) Option { return func(c config) config { c.loggers = append(c.loggers, logger) return c } } // Provides an [Option] which adds the specified [Transformer] to the [ErrorMiddleware] // // Multiple [Transformer] may (and probably should) be added. func WithTransformer(tr Transformer) Option { return func(c config) config { c.transformers = append(c.transformers, tr) return c } } // Provides an [Option] which adds the default [Transformer] to the [ErrorMiddleware] // // This [Transformer] handles a [gin.Error]. func WithDefaultTransformer() Option { return WithTransformer(ginTransformer) } func ginTransformer(er error) rErrors.ResponsableError { var err *gin.Error if !errors.As(er, &err) { return nil } switch err.Type { case gin.ErrorTypePrivate: return rErrors.NewInternalError("%w", err) default: return rErrors.NewBadRequest("%w", err) } }