Skip to content

Commit

Permalink
feat: cosy error struct
Browse files Browse the repository at this point in the history
  • Loading branch information
0xJacky committed Nov 26, 2024
1 parent ce12cf9 commit 3260baa
Showing 1 changed file with 47 additions and 19 deletions.
66 changes: 47 additions & 19 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,63 @@ import (
"errors"
"github.com/gin-gonic/gin"
"github.com/uozi-tech/cosy/logger"
"github.com/uozi-tech/cosy/settings"
"go.uber.org/zap"
"gorm.io/gorm"
"net/http"
)

func errHandler(c *gin.Context, err error) {
logger.GetLogger().WithOptions(zap.AddCallerSkip(1)).Errorln(err)
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusNotFound, gin.H{
"message": err.Error(),
})
return
type Error struct {
Code int32 `json:"code"`
Message string `json:"message"`
}

func (e *Error) Error() string {
return e.Message
}

func NewError(code int32, message string) error {
return &Error{
Code: code,
Message: message,
}
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
}

func ErrHandler(c *gin.Context, err error) {
logger.GetLogger().Errorln(err)
// errorResp error response
func errorResp(c *gin.Context, err error) {
var cErr *Error
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
c.JSON(http.StatusNotFound, &Error{
Code: http.StatusNotFound,
Message: gorm.ErrRecordNotFound.Error(),
})
case errors.As(err, &cErr):
c.JSON(http.StatusInternalServerError, cErr)
default:
if settings.ServerSettings.RunMode == gin.DebugMode {
c.JSON(http.StatusInternalServerError, &Error{
Code: http.StatusInternalServerError,
Message: err.Error(),
})
return
}

if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusNotFound, gin.H{
"message": err.Error(),
c.JSON(http.StatusInternalServerError, &Error{
Code: http.StatusInternalServerError,
Message: "Server Error",
})
return
}
}

// errHandler error handler for internal use
func errHandler(c *gin.Context, err error) {
logger.GetLogger().WithOptions(zap.AddCallerSkip(1)).Errorln(err)
errorResp(c, err)
}

c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
// ErrHandler error handler for external use
func ErrHandler(c *gin.Context, err error) {
logger.GetLogger().Errorln(err)
errorResp(c, err)
}

0 comments on commit 3260baa

Please sign in to comment.