go-zero后端返回函数封装

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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值