hpds_jkw_web/pkg/err/err_encode.go

59 lines
1.5 KiB
Go

package e
import (
"git.hpds.cc/Component/gin_valid/gin/binding"
validator "git.hpds.cc/Component/gin_valid/go-playground/validator/v10"
"github.com/gin-gonic/gin"
"net/http"
)
type WrapperHandle func(c *gin.Context) (interface{}, error)
func ErrorWrapper(handle WrapperHandle) gin.HandlerFunc {
return func(c *gin.Context) {
data, err := handle(c)
if err != nil {
switch r := err.(type) {
case *ApiError:
c.JSON(r.Status, r)
case validator.ValidationErrors:
msg := r.Translate(binding.ValidTrans).Error()
c.JSON(http.StatusOK, gin.H{"code": "", "msg": msg})
default:
er := NewValidErr(err)
c.JSON(http.StatusOK, gin.H{"code": 500, "msg": er.Error()})
}
return
}
if data != nil {
c.JSON(http.StatusOK, data)
} else {
c.JSON(http.StatusOK, gin.H{"code": 200, "data": data})
}
}
}
func ErrorWeChatWrapper(handle WrapperHandle) gin.HandlerFunc {
return func(c *gin.Context) {
data, err := handle(c)
if err != nil {
switch r := err.(type) {
case *ApiError:
c.JSON(r.Status, r)
case validator.ValidationErrors:
msg := r.Translate(binding.ValidTrans).Error()
c.JSON(http.StatusOK, gin.H{"code": "", "msg": msg})
default:
er := NewValidErr(err)
c.JSON(http.StatusOK, gin.H{"code": 500, "msg": er.Error()})
}
return
}
if data != nil {
c.JSON(http.StatusOK, gin.H{"code": "SUCCESS", "data": data})
} else {
c.JSON(http.StatusOK, gin.H{"code": "SUCCESS", "message": "成功"})
}
}
}