Skip to content

Commit

Permalink
feat: add global error handler middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
crazyoptimist committed Jun 16, 2024
1 parent 53cb36b commit e2c8a9c
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 14 deletions.
8 changes: 1 addition & 7 deletions internal/infrastructure/controller/user_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,7 @@ func (u *userController) Create(c *gin.Context) {
// @Router /users/me [post]
// @Security JWT
func (u *userController) Me(c *gin.Context) {
id, _ := c.Get("user")

user, err := u.UserService.FindById(id.(int))
if err != nil {
common.RaiseHttpError(c, http.StatusNotFound, err)
return
}
user, _ := c.Get("user")

c.JSON(http.StatusOK, user)
}
Expand Down
29 changes: 29 additions & 0 deletions internal/infrastructure/middleware/global_error_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package middleware

import (
"errors"
"net/http"

"gin-starter/pkg/common"

"github.com/gin-gonic/gin"
)

func GlobalErrorHandler() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()

for _, err := range c.Errors {
switch e := err.Err.(type) {
case *common.HttpError:
c.AbortWithStatusJSON(e.StatusCode, e)
default:
common.RaiseHttpError(
c,
http.StatusInternalServerError,
errors.New("Service Unavailable"),
)
}
}
}
}
1 change: 1 addition & 0 deletions internal/infrastructure/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func registerRoutes() *gin.Engine {

router.Use(gin.Logger())
router.Use(gin.Recovery())
router.Use(middleware.GlobalErrorHandler())

corsConfig := cors.DefaultConfig()
corsConfig.AllowAllOrigins = true
Expand Down
16 changes: 9 additions & 7 deletions pkg/common/error.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
package common

import "github.com/gin-gonic/gin"
import (
"github.com/gin-gonic/gin"
)

func RaiseHttpError(ctx *gin.Context, status int, err error) {
ctx.AbortWithStatusJSON(status, HttpError{
Code: status,
Message: err.Error(),
func RaiseHttpError(ctx *gin.Context, statusCode int, err error) {
ctx.AbortWithStatusJSON(statusCode, HttpError{
StatusCode: statusCode,
Message: err.Error(),
})
}

// Exporting this in order to use it in API docs
type HttpError struct {
Code int `json:"statusCode" example:"400"`
Message string `json:"message" example:"bad request"`
StatusCode int `json:"statusCode" example:"400"`
Message string `json:"message" example:"Bad Request"`
}

func (e *HttpError) Error() string {
Expand Down

0 comments on commit e2c8a9c

Please sign in to comment.