Go-自定義Error

package common

import (
	"fmt"
)

type ErrCode string

var (
	//common api err message
	SUCCESS       ErrCode = "0"
	DB_UNKNOW_ERR ErrCode = "1001"
)

var errCodeName = map[ErrCode]string{
	SUCCESS:       "Success return",
	DB_UNKNOW_ERR: "Db unknow error",
}

func (e ErrCode) String() string {
	if s, ok := errCodeName[e]; ok {
		return s
	}
	return fmt.Sprintf("unknown error code %s", string(e))
}

type XErrorInfo struct {
	ErrCode ErrCode
	ErrMsg  string
}

func NewXErrorInfo(errCode ErrCode, errMsg string) error {
	globalXErrMgr := XErrorInfo{
		ErrCode: errCode,
		ErrMsg:  errMsg,
	}

	return globalXErrMgr
}

func (e XErrorInfo) Error() string {
	if e.ErrMsg == "" {
		return e.ErrCode.String()
	}
	return e.ErrMsg
}

func (e XErrorInfo) Code() ErrCode {
	return e.ErrCode
}

func XErrToStatusCode(err interface{}, code ErrCode, msg string) (status string, errMsg string) {
	_, ok := err.(XErrorInfo)
	if ok {
		if msg == "" {
			return string(err.(XErrorInfo).Code()), err.(XErrorInfo).Error()
		} else {
			return string(err.(XErrorInfo).Code()), msg
		}
	} else {
		if msg == "" {
			if code == "" {
				return string(code), err.(error).Error()
			} else {
				return string(code), code.String()
			}
		} else {
			return string(code), msg
		}
	}
}

func XErrorEqual(err interface{}, code ErrCode) bool {
	XErr, ok := err.(XErrorInfo)
	if ok {
		return XErr.Code() == code
	}
	return false
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章