gocommon/ginutils/wrapper.go
Matthieu 'JP' DERASSE 77b4351ef1
All checks were successful
continuous-integration/drone/push Build is passing
feat(error): Create api error. WIP
2023-08-22 19:59:44 +00:00

51 lines
1.4 KiB
Go

package ginutils
import (
"net/http"
"git.dev.m-and-m.ovh/mderasse/gocommon/aerr"
"git.dev.m-and-m.ovh/mderasse/gocommon/constant"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// HandlerFunc represent the type of function expected by the wrapper.
type HandlerFunc func(*gin.Context) error
// HandlerWrapper will wrap a handler to handle error.
func HandlerWrapper(h HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
err := h(c)
if err != nil {
errorHandler(c, err)
}
}
}
func errorHandler(c *gin.Context, err error) {
//nolint: errorlint // Ignore linter to avoid creating useless complexity in the code.
switch e := err.(type) {
case *aerr.Error:
log := GetLoggerWithFields(c, logrus.Fields{
string(constant.LogField_Error): e.Error(),
string(constant.LogField_ErrorCode): e.Code,
})
log.Warn("An error occurred")
if e.DebugId == "" {
e = e.SetDebugID(c.GetString(string(constant.ContextKey_RequestID)))
}
c.AbortWithStatusJSON(e.HttpCode(), e)
default:
log := GetLoggerWithFields(c, logrus.Fields{
string(constant.LogField_Error): e.Error(),
string(constant.LogField_ErrorCode): "500",
})
log.Warn("An error occurred")
c.AbortWithStatusJSON(http.StatusInternalServerError, aerr.Error{
Msg: e.Error(),
Code: 500,
DebugId: c.GetString(string(constant.ContextKey_RequestID)),
})
}
}