From 3260baa3e7094ca9565ca0dfe3436400f20f5c85 Mon Sep 17 00:00:00 2001 From: Jacky Date: Tue, 26 Nov 2024 16:18:47 +0800 Subject: [PATCH] feat: cosy error struct --- error.go | 66 ++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 47 insertions(+), 19 deletions(-) diff --git a/error.go b/error.go index 12a3f9b..e50f1a9 100644 --- a/error.go +++ b/error.go @@ -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) }