错误码

package errorsconst (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.MsgCodeData *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 gintonicimport ("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             = 20001pageNotFound             = 20002invalidParameter         = 10001serviceUnavailable       = 10002illegalRequest           = 10003remoteServiceUnreachable = 10004unauthorized             = 10005illegalContent           = 10006captchaFailed            = 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)}
}

 

本文链接:https://my.lmcjl.com/post/7618.html

展开阅读全文

4 评论

留下您的评论.