Skip to content

Commit

Permalink
add a middleware for error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthieu Jacquot committed Jul 28, 2018
1 parent 6e5b00b commit 82315ee
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion implem/gin.server/ROUTER.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/err0r500/go-realworld-clean/uc"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/render"
)

type RouterHandler struct {
Expand All @@ -31,6 +32,8 @@ func NewRouterWithLogger(i uc.Handler, auth uc.AuthHandler, logger uc.Logger) Ro

func (rH RouterHandler) SetRoutes(r *gin.Engine) {
api := r.Group("/api")
api.Use(rH.errorCatcher())

rH.profileRoutes(api)
rH.usersRoutes(api)
rH.articlesRoutes(api)
Expand Down Expand Up @@ -86,7 +89,8 @@ func (rH RouterHandler) jwtMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
userName, err := rH.authHandler.GetUserName(c.GetHeader("Authorization"))
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
c.Status(http.StatusUnauthorized)
c.Abort()
return
}
c.SetAccepted()
Expand All @@ -95,6 +99,21 @@ func (rH RouterHandler) jwtMiddleware() gin.HandlerFunc {
}
}

func (rH RouterHandler) errorCatcher() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if c.Writer.Status() > 399 {
c.Render(
c.Writer.Status(),
render.Data{
ContentType: "application/json; charset=utf-8",
Data: []byte(`{"errors": {"body": ["wooops, something went wrong !"]}}`),
},
)
}
}
}

func (RouterHandler) getUserName(c *gin.Context) string {
if userName, ok := c.Keys[userNameKey].(string); ok {
return userName
Expand Down

0 comments on commit 82315ee

Please sign in to comment.