错误码

package errors

const (
   InternalError = 10001 //内部错误 非crm  //InternalError就是10001,后端其他同学使用InternalError比直接用10001更人性化一点

   //crm错误码
   InvalidParameter          = 100 //无效的参数
   EmailExistded             = 101 //邮箱已占用
   InvalidEmail              = 102 //无效的邮箱
   MobileExistded            = 103 //手机号码已占用
   InvalidMobile             = 104 //无效的手机号码
   VerificationCodeNotExist  = 105 //验证码不存在
   VerificationCodeExisted   = 106 //验证码已经验证过
   UnionIDExisted            = 107 //UnionID已占用
   MemberIDMismatchPetID     = 108 //会员ID与宠物ID不匹配
   MemberIDMismatchAddressID = 109 //会员ID与地址ID不匹配
   NullParameter             = 110 //参数不能为空
   CouponNull                = 200 //优惠券已领完
   CouponExisted             = 201 //你已经领过该优惠券
   CouponUnused              = 202 //优惠券未使用
   CouponUnusedUsed          = 203 //优惠券已使用
   CouponExpired             = 204 //优惠券已过期
   CouponUneffect            = 205 //优惠券未到使用日期
   CrmInternalError          = 999 //crm系统错误
)

type CrmError struct {
   StatusCode int    `json:"statusCode"` //http状态码
   ErrCode    int    `json:"errCode"`    //错误码
   Message    string `json:"message"`    //错误信息
}
//判断方式
if CrmError != nil {
	if StatusCode == 0 {  //crm调通
		//再判断ErrCode
	}
	if StatusCode != 200 {	//crm调不通
	}
} else {
	//没有错误
}
func (c *memberCrmStore) doGet(url string, params map[string]string, v interface{}) *errors.CrmError {
   req, err := http.NewRequest("GET", CrmHost+url, nil)
   if err != nil {
      return &errors.CrmError{ErrCode: errors.InternalError, Message: err.Error()}
   }
   q := req.URL.Query()
   for k, v := range params {
      if v != "" {
         q.Add(k, v)
      }
   }
   req.URL.RawQuery = q.Encode()

   //打印请求数据
   logrus.Infof("Request Info: %s", req.URL)

   resp, err := c.CrmClient.Do(req)
   if err != nil {
      return &errors.CrmError{ErrCode: errors.InternalError, Message: err.Error()}
   }
   defer resp.Body.Close()

   body, err := ioutil.ReadAll(resp.Body)
   if err != nil {
      return &errors.CrmError{ErrCode: errors.InternalError, Message: err.Error()}
   }

   //打印返回数据
   logrus.Infof("Response Info: %s", body)

   if resp.StatusCode != http.StatusOK {
      logrus.Infof("crm error: %s", string(body))
      return &errors.CrmError{StatusCode: resp.StatusCode, Message: string(body)}
   }

   if err := json.Unmarshal(body, v); err != nil {
      return &errors.CrmError{ErrCode: errors.InternalError, Message: err.Error()}
   }

   return nil
}
func (c *memberCrmStore) MemberGet(memberQueryReq *request.MemberQueryReq) (*model.Member, *errors.CrmError) {
   params := map[string]string{
      "id":        strconv.Itoa(memberQueryReq.Id),
      "channelId": strconv.Itoa(memberQueryReq.ChannelId),
      "mobile":    memberQueryReq.Mobile,
      "unionId":   memberQueryReq.UnionId,
      "pet":       strconv.FormatBool(memberQueryReq.Pet),
      "address":   strconv.FormatBool(memberQueryReq.Address),
   }

   type Body struct {
      response.MsgCode
      Data *model.Member `json:"data"`
   }
   entity := &Body{}
   crmErr := MemberCrm.doGet("/member/get", params, entity)
   if crmErr != nil {
      return nil, crmErr
   }

   if entity.Code != "1" && entity.Code != "0" {
      errCode, _ := strconv.Atoi(entity.Code)
      return nil, &errors.CrmError{ErrCode: errCode}
   }

   return entity.Data, nil
}

 

其他参考:

package gintonic

import (
	"encoding/json"
	"net/http"

	"github.com/sirupsen/logrus"
)

type Error struct {
	StatusCode int               `json:"statusCode"`
	ErrCode    int               `json:"code"`
	Message    string            `json:"message"`
	Data       map[string]string `json:"data,omitempty"`
}

func (e Error) Error() string {
	bs, _ := json.Marshal(e)
	return string(bs)
}

func ParseError(bytes []byte) Error {
	err := Error{}
	if err := json.Unmarshal(bytes, &err); err != nil {
		return ErrServiceUnavailable
	}
	return err
}

const (
	unknownError             = 20001
	pageNotFound             = 20002
	invalidParameter         = 10001
	serviceUnavailable       = 10002
	illegalRequest           = 10003
	remoteServiceUnreachable = 10004
	unauthorized             = 10005
	illegalContent           = 10006
	captchaFailed            = 10007
)

var (
	ErrUnknownError = Error{
		StatusCode: http.StatusInternalServerError,
		ErrCode:    unknownError,
		Message:    "unknown error",
	}
	ErrPageNotFound = Error{
		StatusCode: http.StatusNotFound,
		ErrCode:    pageNotFound,
		Message:    "page not found",
	}

	ErrInvalidParameter = Error{
		StatusCode: http.StatusBadRequest,
		ErrCode:    invalidParameter,
		Message:    "invalid request parameter",
	}
	ErrServiceUnavailable = Error{
		StatusCode: http.StatusInternalServerError,
		ErrCode:    serviceUnavailable,
		Message:    "service unavailable temporarily",
	}
	ErrIllegalRequest = Error{
		StatusCode: http.StatusBadRequest,
		ErrCode:    illegalRequest,
		Message:    "illegal request",
	}
	ErrRemoteServiceUnreachable = Error{
		StatusCode: http.StatusInternalServerError,
		ErrCode:    remoteServiceUnreachable,
		Message:    "remote service unreachable",
	}
	ErrUnauthorized = Error{
		StatusCode: http.StatusUnauthorized,
		ErrCode:    unauthorized,
		Message:    "unauthorized",
	}
	ErrIllegalContent = Error{
		StatusCode: http.StatusBadRequest,
		ErrCode:    illegalContent,
		Message:    "content illegal",
	}
	ErrCaptchaFailed = Error{
		StatusCode: http.StatusForbidden,
		ErrCode:    captchaFailed,
		Message:    "captcha failed",
	}
)

func MakeErrorHandler(err error) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err == nil {
			return
		}

		e, ok := err.(Error)
		if !ok {
			logrus.Errorf("unknown error: %v", err)
			e = ErrUnknownError
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(e.StatusCode)
		enc := json.NewEncoder(w)
		enc.SetEscapeHTML(false)
		enc.Encode(e)
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值