Skip to content

Commit e7a7c94

Browse files
committed
fea: added bindErrorToCtx
1 parent f757675 commit e7a7c94

2 files changed

Lines changed: 21 additions & 10 deletions

File tree

presentation/rest/controller_account.go

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,23 +30,20 @@ func (c *accountController) Get(ctx *gin.Context) {
3030
paging, err := paging(ctx.Query("paging"))
3131
if err != nil {
3232
// set error to Gin context so that the logging middleware can access it
33-
ctx.Error(err)
34-
ctx.JSON(http.StatusUnprocessableEntity, responseError(err))
33+
bindErrorToCtx(ctx, err, http.StatusUnprocessableEntity)
3534
return
3635
}
3736

3837
filters, err := filters(ctx.Query("filters"))
3938
if err != nil {
40-
ctx.Error(err)
41-
ctx.JSON(http.StatusUnprocessableEntity, responseError(err))
39+
bindErrorToCtx(ctx, err, http.StatusUnprocessableEntity)
4240
return
4341
}
4442

4543
// pass on to the usecase
4644
data, err := c.accounts.GetAccounts(context.Background(), filters, paging)
4745
if err != nil {
48-
ctx.Error(err)
49-
ctx.JSON(http.StatusBadRequest, responseError(err))
46+
bindErrorToCtx(ctx, err, http.StatusBadRequest)
5047
return
5148
}
5249

@@ -58,8 +55,7 @@ func (c *accountController) Create(ctx *gin.Context) {
5855
// get data from request and validate (gin does this under the hood using 'go-playground/validator/v10')
5956
var reqBody accountRequest
6057
if err := ctx.ShouldBindJSON(&reqBody); err != nil {
61-
ctx.Error(err)
62-
ctx.JSON(http.StatusUnprocessableEntity, responseError(err))
58+
bindErrorToCtx(ctx, err, http.StatusUnprocessableEntity)
6359
return
6460
}
6561

@@ -71,8 +67,7 @@ func (c *accountController) Create(ctx *gin.Context) {
7167
// pass on to the usecase
7268
data, err := c.accounts.CreateAccount(context.Background(), a)
7369
if err != nil {
74-
ctx.Error(err)
75-
ctx.JSON(http.StatusBadRequest, responseError(err))
70+
bindErrorToCtx(ctx, err, http.StatusBadRequest)
7671
return
7772
}
7873

presentation/rest/helpers.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package rest
2+
3+
import (
4+
"github.com/gin-gonic/gin"
5+
)
6+
7+
// bindErrorToCtx is a helper function that sets the error
8+
// in the gin context so that it is accessible by th logger
9+
// and the response.
10+
func bindErrorToCtx(ctx *gin.Context, err error, httpStatus int) {
11+
// read by the logger
12+
ctx.Error(err)
13+
14+
// error response from rest server
15+
ctx.JSON(httpStatus, responseError(err))
16+
}

0 commit comments

Comments
 (0)