You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1022 B
Go

package utils
import (
syserrors "errors"
"github.com/gin-gonic/gin"
"gold-shop/errors"
)
type Result struct {
Code string `json:"code"`
Message string `json:"message"`
Data Data `json:"data"`
}
type Data map[string]interface{}
func JsonHandler(api func(c *gin.Context) (Data, error)) func(c *gin.Context) {
return func(c *gin.Context) {
data, err := api(c)
result := Result{}
if err != nil {
result = buildErrorResult(err)
result.Data = data
} else {
result.Code = Success
result.Message = "成功"
result.Data = data
}
c.JSON(200, result)
}
}
func Handler(api func(c *gin.Context)) func(c *gin.Context) {
return api
}
func buildErrorResult(err error) Result {
result := Result{}
switch err.(type) {
case *errors.BusinessError:
var businessError *errors.BusinessError
syserrors.As(err, &businessError)
result.Code = businessError.Code
result.Message = businessError.Message
default:
result.Code = Error
result.Message = "系统异常"
}
return result
}