🔊 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)
|
re = rErrors.NewInternalError("%w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, logger := range conf.loggers {
|
||||||
|
logger(c, re)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Set("rendered_error", re)
|
||||||
|
|
||||||
c.JSON(re.Status(), re)
|
c.JSON(re.Status(), re)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
rErrors "codeberg.org/danjones000/responsable-errors"
|
rErrors "codeberg.org/danjones000/responsable-errors"
|
||||||
|
|
@ -117,3 +118,15 @@ func (s *MiddlewareTestSuite) TestNoWorkingTransformer() {
|
||||||
s.Assert().Equal("Unknown Error", outMsg)
|
s.Assert().Equal("Unknown Error", outMsg)
|
||||||
s.Assert().Equal(http.StatusInternalServerError, s.w.Code)
|
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 {
|
type config struct {
|
||||||
|
loggers []LoggerFunc
|
||||||
transformers []Transformer
|
transformers []Transformer
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type LoggerFunc func(*gin.Context, rErrors.ResponsableError)
|
||||||
|
|
||||||
type Transformer func(error) rErrors.ResponsableError
|
type Transformer func(error) rErrors.ResponsableError
|
||||||
|
|
||||||
type Option func(config) config
|
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 {
|
func WithTransformer(tr Transformer) Option {
|
||||||
return func(c config) config {
|
return func(c config) config {
|
||||||
c.transformers = append(c.transformers, tr)
|
c.transformers = append(c.transformers, tr)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue