改之前

在应用 gin 开发接口的时候,返回接口数据是这样写的。

type response struct {    Code int         `json:"code"`    Msg  string      `json:"msg"`    Data interface{} `json:"data"`}// always return http.StatusOKc.JSON(http.StatusOK, response{    Code: 20101,    Msg:  "用户手机号不非法",    Data: nil,})

这种写法 codemsg 都是在哪须要返回在哪定义,没有进行对立治理。

改之后

// 比方,返回“用户手机号不非法”谬误c.JSON(http.StatusOK, errno.ErrUserPhone.WithID(c.GetString("trace-id")))// 正确返回c.JSON(http.StatusOK, errno.OK.WithData(data).WithID(c.GetString("trace-id")))

errno.ErrUserPhoneerrno.OK 示意自定义的错误码,上面会看到定义的中央。

.WithID() 设置以后申请的惟一ID,也能够了解为链路ID,疏忽也能够。

.WithData() 设置胜利时返回的数据。

上面分享下编写的 errno 包源码,非常简单,心愿大家不要介意。

errno 包源码

// errno/errno.gopackage errnoimport (    "encoding/json")var _ Error = (*err)(nil)type Error interface {    // i 为了防止被其余包实现    i()    // WithData 设置胜利时返回的数据    WithData(data interface{}) Error    // WithID 设置以后申请的惟一ID    WithID(id string) Error    // ToString 返回 JSON 格局的谬误详情    ToString() string}type err struct {    Code int         `json:"code"`         // 业务编码    Msg  string      `json:"msg"`          // 谬误形容    Data interface{} `json:"data"`         // 胜利时返回的数据    ID   string      `json:"id,omitempty"` // 以后申请的惟一ID,便于问题定位,疏忽也能够}func NewError(code int, msg string) Error {    return &err{        Code: code,        Msg:  msg,        Data: nil,    }}func (e *err) i() {}func (e *err) WithData(data interface{}) Error {    e.Data = data    return e}func (e *err) WithID(id string) Error {    e.ID = id    return e}// ToString 返回 JSON 格局的谬误详情func (e *err) ToString() string {    err := &struct {        Code int         `json:"code"`        Msg  string      `json:"msg"`        Data interface{} `json:"data"`        ID   string      `json:"id,omitempty"`    }{        Code: e.Code,        Msg:  e.Msg,        Data: e.Data,        ID:   e.ID,    }    raw, _ := json.Marshal(err)    return string(raw)}
// errno/code.gopackage errnovar (    // OK    OK = NewError(0, "OK")    // 服务级错误码    ErrServer    = NewError(10001, "服务异样,请分割管理员")    ErrParam     = NewError(10002, "参数有误")    ErrSignParam = NewError(10003, "签名参数有误")    // 模块级错误码 - 用户模块    ErrUserPhone   = NewError(20101, "用户手机号不非法")    ErrUserCaptcha = NewError(20102, "用户验证码有误")    // ...)

错误码规定

  • 错误码需在 code.go 文件中定义。
  • 错误码需为 > 0 的数,反之示意正确。

错误码为 5 位数

10101
服务级错误码模块级错误码具体错误码
  • 服务级别错误码:1 位数进行示意,比方 1 为零碎级谬误;2 为一般谬误,通常是由用户非法操作引起。
  • 模块级错误码:2 位数进行示意,比方 01 为用户模块;02 为订单模块。
  • 具体错误码:2 位数进行示意,比方 01 为手机号不非法;02 为验证码输出谬误。

以上代码在 go-gin-api 我的项目中,地址:https://github.com/xinliangno...