🔊 Add WithLogger so we can log the rendered error
This commit is contained in:
parent
b4b4f041d7
commit
2324d738bc
3 changed files with 29 additions and 0 deletions
|
|
@ -48,6 +48,12 @@ func ErrorMiddleware(opts ...Option) gin.HandlerFunc {
|
|||
re = rErrors.NewInternalError("%w", err)
|
||||
}
|
||||
|
||||
for _, logger := range conf.loggers {
|
||||
logger(c, re)
|
||||
}
|
||||
|
||||
c.Set("rendered_error", re)
|
||||
|
||||
c.JSON(re.Status(), re)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
rErrors "codeberg.org/danjones000/responsable-errors"
|
||||
|
|
@ -117,3 +118,15 @@ func (s *MiddlewareTestSuite) TestNoWorkingTransformer() {
|
|||
s.Assert().Equal("Unknown Error", outMsg)
|
||||
s.Assert().Equal(http.StatusInternalServerError, s.w.Code)
|
||||
}
|
||||
|
||||
func (s *MiddlewareTestSuite) TestLogger() {
|
||||
buff := strings.Builder{}
|
||||
var l LoggerFunc = func(c *gin.Context, err rErrors.ResponsableError) {
|
||||
buff.WriteString("Err: " + err.Error())
|
||||
}
|
||||
err := errors.New("Foo")
|
||||
s.ctx.Error(err)
|
||||
ErrorMiddleware(WithLogger(l))(s.ctx)
|
||||
|
||||
s.Assert().Equal("Err: Foo", buff.String())
|
||||
}
|
||||
|
|
|
|||
10
options.go
10
options.go
|
|
@ -8,13 +8,23 @@ import (
|
|||
)
|
||||
|
||||
type config struct {
|
||||
loggers []LoggerFunc
|
||||
transformers []Transformer
|
||||
}
|
||||
|
||||
type LoggerFunc func(*gin.Context, rErrors.ResponsableError)
|
||||
|
||||
type Transformer func(error) rErrors.ResponsableError
|
||||
|
||||
type Option func(config) config
|
||||
|
||||
func WithLogger(logger LoggerFunc) Option {
|
||||
return func(c config) config {
|
||||
c.loggers = append(c.loggers, logger)
|
||||
return c
|
||||
}
|
||||
}
|
||||
|
||||
func WithTransformer(tr Transformer) Option {
|
||||
return func(c config) config {
|
||||
c.transformers = append(c.transformers, tr)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue