package response_demo
import (
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"google.golang.org/grpc/status"
"net/http"
)
const (
Success uint32 = 0
ServiceErr uint32 = 500 + iota
)
var errText = map[uint32]string{
Success: "成功",
ServiceErr: "服务内部错误",
}
type ResponseWithDataBean struct {
Code uint32 `json:"code"`
Msg *string `json:"msg"`
Data interface{} `json:"data"`
Error *string `json:"error"`
}
type ResponseBean struct {
Code uint32 `json:"code"`
Msg *string `json:"msg"`
}
func SuccessWithData(data interface{}) *ResponseWithDataBean {
msg := "成功!"
return &ResponseWithDataBean{
Code: 200,
Msg: &msg,
Data: data,
}
}
func Error(errCode uint32, errMsg string) *ResponseBean {
return &ResponseBean{errCode, &errMsg}
}
type ErrCodeAndMsg struct {
Code uint32 `json:"code"`
Msg string `json:"msg"`
}
func Response(w http.ResponseWriter, resp interface{}, err error, r *http.Request) {
if err != nil {
errcode := ServiceErr
errmsg := ErrText(errcode)
causeErr := errors.Cause(err) // err类型
if e, ok := causeErr.(*ErrCodeAndMsg); ok { // 自定义错误类型
errcode = e.Code
errmsg = e.Msg
} else {
if gstatus, ok := status.FromError(causeErr); ok { // grpc错误
grpcCode := uint32(gstatus.Code())
if IsCodeErr(grpcCode) { // 自定义错误
errcode = grpcCode
errmsg = gstatus.Message()
} else {
logx.Errorf("【%s】%s", errmsg, err.Error())
}
}
}
s := err.Error()
s2 := `desc = `
if strings.Contains(s, s2) {
s = s[strings.Index(s, s2)+len(s2):]
}
r := Error(errcode, errmsg+":"+s+"")
httpx.WriteJson(w, http.StatusOK, r)
} else {
r := SuccessWithData(resp)
httpx.WriteJson(w, http.StatusOK, r)
}
}
func NewError(code uint32, fileds ...string) error {
msg := ErrText(code)
if len(fileds) > 0 {
filed := fmt.Sprintf(",输入的%s已存在,请重新输入!", fileds[0])
msg += filed
}
return &ErrCodeAndMsg{Code: code, Msg: msg}
}
func ErrText(code uint32) string {
return errText[code]
}
func IsCodeErr(code uint32) bool {
if _, ok := errText[code]; ok {
return true
} else {
return false
}
}
func (e *ErrCodeAndMsg) Error() string {
return e.Msg
}
go-zero后端返回函数封装
最新推荐文章于 2024-11-08 16:27:21 发布