This commit is contained in:
withchao 2023-03-24 17:34:00 +08:00
parent 5017c61e28
commit 429d5da1d2
2 changed files with 12 additions and 13 deletions

View File

@ -6,13 +6,9 @@ import (
) )
func GinError(c *gin.Context, err error) { func GinError(c *gin.Context, err error) {
if err == nil { c.JSON(http.StatusOK, ApiError(err))
GinSuccess(c, nil)
return
}
c.JSON(http.StatusOK, apiError(err))
} }
func GinSuccess(c *gin.Context, data any) { func GinSuccess(c *gin.Context, data any) {
c.JSON(http.StatusOK, apiSuccess(data)) c.JSON(http.StatusOK, ApiSuccess(data))
} }

View File

@ -5,7 +5,7 @@ import (
"reflect" "reflect"
) )
type apiResponse struct { type ApiCodeResponse struct {
ErrCode int `json:"errCode"` ErrCode int `json:"errCode"`
ErrMsg string `json:"errMsg"` ErrMsg string `json:"errMsg"`
ErrDlt string `json:"errDlt"` ErrDlt string `json:"errDlt"`
@ -30,23 +30,26 @@ func isAllFieldsPrivate(v any) bool {
return true return true
} }
func apiSuccess(data any) *apiResponse { func ApiSuccess(data any) *ApiCodeResponse {
if isAllFieldsPrivate(data) { if isAllFieldsPrivate(data) {
return &apiResponse{} return &ApiCodeResponse{}
} }
return &apiResponse{ return &ApiCodeResponse{
Data: data, Data: data,
} }
} }
func apiError(err error) *apiResponse { func ApiError(err error) *ApiCodeResponse {
if err == nil {
return ApiSuccess(nil)
}
unwrap := errs.Unwrap(err) unwrap := errs.Unwrap(err)
if codeErr, ok := unwrap.(errs.CodeError); ok { if codeErr, ok := unwrap.(errs.CodeError); ok {
resp := apiResponse{ErrCode: codeErr.Code(), ErrMsg: codeErr.Msg(), ErrDlt: codeErr.Detail()} resp := ApiCodeResponse{ErrCode: codeErr.Code(), ErrMsg: codeErr.Msg(), ErrDlt: codeErr.Detail()}
if resp.ErrDlt == "" { if resp.ErrDlt == "" {
resp.ErrDlt = err.Error() resp.ErrDlt = err.Error()
} }
return &resp return &resp
} }
return &apiResponse{ErrCode: errs.ServerInternalError, ErrMsg: err.Error()} return &ApiCodeResponse{ErrCode: errs.ServerInternalError, ErrMsg: err.Error()}
} }