diff --git a/internal/api/code/code.go b/internal/api/code/code.go index 2e58e37..339077e 100644 --- a/internal/api/code/code.go +++ b/internal/api/code/code.go @@ -8,22 +8,20 @@ import ( var ( // OK - OK = errno.NewError(1, "OK") + OK = errno.NewError(http.StatusOK, 1, "OK") // 服务级错误码 - ErrServer = errno.NewError(10101, http.StatusText(http.StatusInternalServerError)) - ErrManyRequest = errno.NewError(10102, "Too many requests") - - ErrParam = errno.NewError(10110, "参数有误") - ErrSignParam = errno.NewError(10111, "缺少签名") - ErrSign = errno.NewError(10112, "签名有误") + ErrServer = errno.NewError(http.StatusInternalServerError, 10101, http.StatusText(http.StatusInternalServerError)) + ErrManyRequest = errno.NewError(http.StatusTooManyRequests, 10102, http.StatusText(http.StatusTooManyRequests)) + ErrParamBind = errno.NewError(http.StatusBadRequest, 10103, "参数信息有误") + ErrAuthorization = errno.NewError(http.StatusUnauthorized, 10104, "签名信息有误") // 模块级错误码 - 用户模块 - ErrUser = errno.NewError(20101, "非法用户") - ErrUserCreate = errno.NewError(20102, "创建用户失败") - ErrUserUpdate = errno.NewError(20103, "更新用户失败") - ErrUserSearch = errno.NewError(20104, "查询用户失败") - ErrUserHTTP = errno.NewError(20105, "调用他方接口失败") + ErrUser = errno.NewError(http.StatusBadRequest, 20101, "非法用户") + ErrUserCreate = errno.NewError(http.StatusBadRequest, 20102, "创建用户失败") + ErrUserUpdate = errno.NewError(http.StatusBadRequest, 20103, "更新用户失败") + ErrUserSearch = errno.NewError(http.StatusBadRequest, 20104, "查询用户失败") + ErrUserHTTP = errno.NewError(http.StatusBadRequest, 20105, "调用他方接口失败") // ... ) diff --git a/internal/api/controller/demo/demo.go b/internal/api/controller/demo/demo.go index 027f6bb..c339d9e 100644 --- a/internal/api/controller/demo/demo.go +++ b/internal/api/controller/demo/demo.go @@ -35,12 +35,12 @@ func (d *Demo) Get() core.HandlerFunc { return func(c core.Context) { req := new(request) if err := c.ShouldBindURI(req); err != nil { - c.SetPayload(code.ErrParam) + c.AbortWithError(code.ErrParamBind) return } if req.Name != "Tom" { - c.SetPayload(code.ErrUser) + c.AbortWithError(code.ErrUser) return } @@ -64,12 +64,12 @@ func (d *Demo) Post() core.HandlerFunc { return func(c core.Context) { req := new(request) if err := c.ShouldBindPostForm(req); err != nil { - c.SetPayload(code.ErrParam) + c.AbortWithError(code.ErrParamBind) return } if req.Name != "Jack" { - c.SetPayload(code.ErrUser) + c.AbortWithError(code.ErrUser) return } @@ -103,15 +103,16 @@ func (d *Demo) User() core.HandlerFunc { return func(c core.Context) { req := new(request) if err := c.ShouldBindURI(req); err != nil { - c.SetPayload(code.ErrParam) + c.AbortWithError(code.ErrParamBind) return } if req.Name != "Tom" { - c.SetPayload(code.ErrUser) + c.AbortWithError(code.ErrUser) return } + res1, err := go_gin_api_repo.DemoGet(req.Name, httpclient.WithTTL(time.Second*5), httpclient.WithTrace(c.Trace()), @@ -122,7 +123,8 @@ func (d *Demo) User() core.HandlerFunc { if err != nil { d.logger.Error("get [demo/get] err", zap.Error(err)) - c.SetPayload(code.ErrUserHTTP) + c.AbortWithError(code.ErrUserHTTP) + return } res2, err := go_gin_api_repo.DemoPost("Jack", @@ -135,7 +137,8 @@ func (d *Demo) User() core.HandlerFunc { if err != nil { d.logger.Error("post [demo/post] err", zap.Error(err)) - c.SetPayload(code.ErrUserHTTP) + c.AbortWithError(code.ErrUserHTTP) + return } data := &response{ diff --git a/internal/api/controller/user_handler/user.go b/internal/api/controller/user_handler/user.go index e05f4b4..0f5b350 100644 --- a/internal/api/controller/user_handler/user.go +++ b/internal/api/controller/user_handler/user.go @@ -57,14 +57,14 @@ func (u *userDemo) Create() core.HandlerFunc { res := new(user_model.CreateResponse) if err := c.ShouldBindJSON(req); err != nil { u.logger.Error("[user] should bind json err", zap.Error(err)) - c.SetPayload(code.ErrParam) + c.AbortWithError(code.ErrParamBind) return } id, err := u.userService.Create(c, req) if err != nil { u.logger.Error("[user] Create err", zap.Error(err)) - c.SetPayload(code.ErrUserCreate) + c.AbortWithError(code.ErrUserCreate) return } @@ -88,14 +88,14 @@ func (u *userDemo) UpdateNickNameByID() core.HandlerFunc { res := new(user_model.UpdateNickNameByIDResponse) if err := c.ShouldBindJSON(req); err != nil { u.logger.Error("[user] should bind json err", zap.Error(err)) - c.SetPayload(code.ErrParam) + c.AbortWithError(code.ErrParamBind) return } err := u.userService.UpdateNickNameByID(c, req.Id, req.NickName) if err != nil { u.logger.Error("[user] UpdateNickNameByID err", zap.Error(err)) - c.SetPayload(code.ErrUserUpdate) + c.AbortWithError(code.ErrUserUpdate) return } @@ -119,7 +119,7 @@ func (u *userDemo) Login() core.HandlerFunc { res := new(user_model.LoginResponse) if err := c.ShouldBindJSON(req); err != nil { u.logger.Error("should bind json err", zap.Error(err)) - c.SetPayload(code.ErrParam) + c.AbortWithError(code.ErrParamBind) return } @@ -127,14 +127,14 @@ func (u *userDemo) Login() core.HandlerFunc { tokenString, err := token.New(cfg.Secret).Sign(req.UserID, req.UserName) if err != nil { u.logger.Error("token sign err", zap.Error(err)) - c.SetPayload(code.ErrSign) + c.AbortWithError(code.ErrAuthorization) return } claims, err := token.New(cfg.Secret).Parse(tokenString) if err != nil { u.logger.Error("token parse err", zap.Error(err)) - c.SetPayload(code.ErrSign) + c.AbortWithError(code.ErrAuthorization) return } @@ -160,14 +160,14 @@ func (u *userDemo) Detail() core.HandlerFunc { res := new(user_model.DetailResponse) if err := c.ShouldBindURI(req); err != nil { u.logger.Error("should bind uri err", zap.Error(err)) - c.SetPayload(code.ErrParam) + c.AbortWithError(code.ErrParamBind) return } user, err := u.userService.GetUserByUserName(c, req.UserName) if err != nil { u.logger.Error("[user] GetUserByUserName err", zap.Error(err)) - c.SetPayload(code.ErrUserSearch) + c.AbortWithError(code.ErrUserSearch) return } diff --git a/internal/api/router/middleware/auth.go b/internal/api/router/middleware/auth.go index 105f352..7ded664 100644 --- a/internal/api/router/middleware/auth.go +++ b/internal/api/router/middleware/auth.go @@ -11,20 +11,20 @@ import ( func AuthHandler(ctx core.Context) (userId int, userName string, err errno.Error) { auth := ctx.GetHeader("Authorization") if auth == "" { - err = code.ErrSignParam + err = code.ErrAuthorization return } cfg := configs.Get().JWT claims, errParse := token.New(cfg.Secret).Parse(auth) if errParse != nil { - err = code.ErrSignParam + err = code.ErrAuthorization return } userId = claims.UserID if userId <= 0 { - err = code.ErrSignParam + err = code.ErrAuthorization return } userName = claims.UserName diff --git a/internal/pkg/core/context.go b/internal/pkg/core/context.go index c2a93b9..f610cf4 100644 --- a/internal/pkg/core/context.go +++ b/internal/pkg/core/context.go @@ -255,7 +255,12 @@ func (c *context) setUserName(userName string) { func (c *context) AbortWithError(err errno.Error) { if err != nil { - c.ctx.AbortWithStatus(http.StatusInternalServerError) + httpCode := err.GetHttpCode() + if httpCode == 0 { + httpCode = http.StatusInternalServerError + } + + c.ctx.AbortWithStatus(httpCode) c.ctx.Set(_AbortErrorName, err) } } diff --git a/internal/pkg/core/core.go b/internal/pkg/core/core.go index 80534a0..08c880e 100644 --- a/internal/pkg/core/core.go +++ b/internal/pkg/core/core.go @@ -125,6 +125,7 @@ func WrapAuthHandler(handler func(Context) (userID int, userName string, err err return func(ctx Context) { userID, userName, err := handler(ctx) if err != nil { + ctx.Logger().Error("auth handler err", zap.Error(errors.WithStack(errors.New(err.GetMsg())))) ctx.AbortWithError(err) return } @@ -336,7 +337,7 @@ func New(logger *zap.Logger, options ...Option) (Mux, error) { if err := recover(); err != nil { stackInfo := string(debug.Stack()) logger.Error("got panic", zap.String("panic", fmt.Sprintf("%+v", err)), zap.String("stack", stackInfo)) - context.SetPayload(code.ErrServer) + context.AbortWithError(code.ErrServer) if notify := opt.panicNotify; notify != nil { notify(context, err, stackInfo) @@ -376,9 +377,10 @@ func New(logger *zap.Logger, options ...Option) (Mux, error) { } else { response.WithID("") } - businessCode = response.GetCode() + + businessCode = response.GetBusinessCode() businessCodeMsg = response.GetMsg() - ctx.JSON(http.StatusOK, response) + ctx.JSON(response.GetHttpCode(), response) } if opt.recordMetrics != nil { diff --git a/pkg/errno/errno.go b/pkg/errno/errno.go index 641d058..d9269ca 100644 --- a/pkg/errno/errno.go +++ b/pkg/errno/errno.go @@ -13,8 +13,10 @@ type Error interface { WithData(data interface{}) Error // WithID 设置当前请求的唯一ID WithID(id string) Error - // GetCode 获取 Code - GetCode() int + // GetBusinessCode 获取 Business Code + GetBusinessCode() int + // GetHttpCode 获取 HTTP Code + GetHttpCode() int // GetMsg 获取 Msg GetMsg() string // ToString 返回 JSON 格式的错误详情 @@ -22,17 +24,19 @@ type Error interface { } type err struct { - Code int `json:"code"` // 业务编码 - Msg string `json:"msg"` // 错误描述 - Data interface{} `json:"data"` // 成功时返回的数据 - ID string `json:"id,omitempty"` // 当前请求的唯一ID,便于问题定位,忽略也可以 + HttpCode int `json:"-"` // HTTP Code + BusinessCode int `json:"code"` // Business Code + Msg string `json:"msg"` // 错误描述 + Data interface{} `json:"data"` // 成功时返回的数据 + ID string `json:"id,omitempty"` // 当前请求的唯一ID,便于问题定位,忽略也可以 } -func NewError(code int, msg string) Error { +func NewError(httpCode, businessCode int, msg string) Error { return &err{ - Code: code, - Msg: msg, - Data: nil, + HttpCode: httpCode, + BusinessCode: businessCode, + Msg: msg, + Data: nil, } } @@ -48,8 +52,12 @@ func (e *err) WithID(id string) Error { return e } -func (e *err) GetCode() int { - return e.Code +func (e *err) GetHttpCode() int { + return e.HttpCode +} + +func (e *err) GetBusinessCode() int { + return e.BusinessCode } func (e *err) GetMsg() string { @@ -59,15 +67,17 @@ func (e *err) GetMsg() string { // ToString 返回 JSON 格式的错误详情 func (e *err) ToString() string { err := &struct { - Code int `json:"code"` - Msg string `json:"msg"` - Data interface{} `json:"data"` - ID string `json:"id,omitempty"` + HttpCode int `json:"http_code"` + BusinessCode int `json:"business_code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + ID string `json:"id,omitempty"` }{ - Code: e.Code, - Msg: e.Msg, - Data: e.Data, - ID: e.ID, + HttpCode: e.HttpCode, + BusinessCode: e.BusinessCode, + Msg: e.Msg, + Data: e.Data, + ID: e.ID, } raw, _ := json.Marshal(err)