作者 唐旭辉

修改错误处理

... ... @@ -4,11 +4,26 @@ import (
"encoding/json"
)
//CustomErrParse 解析自定义错误结构体
type CustomErrParse interface {
ParseToMessage() interface{}
ParseToMessage() *ResponseMessage
}
//ErrorCode 统一错误编码结构
//ErrorMap 统一消息错误编码
type ErrorMap map[int]string
//Search 搜索错误描述
func (m ErrorMap) Search(code int) ErrorCode {
if v, ok := m[code]; ok {
return ErrorCode{
Errno: code,
Errmsg: v,
}
}
return ErrorCode{}
}
//ErrorCode 统一错误结构
type ErrorCode struct {
Errno int `json:"code"`
Errmsg string `json:"msg"`
... ... @@ -22,22 +37,27 @@ type ResponseMessage struct {
func NewMesage(code int) *ResponseMessage {
return &ResponseMessage{
ErrorCode: errmessge.Search(code),
ErrorCode: SearchErr(code),
Data: nil,
}
}
//ErrWithMessage 自定义错误结构
type ErrWithMessage struct {
Err error
Err error `json:"-"`
ErrorCode
}
var (
_ CustomErrParse = new(ErrWithMessage)
_ error = new(ErrWithMessage)
)
//NewErrWithMessage 构建错误返回
//code:用于匹配统一消息错误编码 eRR:填充嵌套错误
func NewErrWithMessage(code int, eRR ...error) *ErrWithMessage {
r := &ErrWithMessage{
ErrorCode: errmessge.Search(code),
ErrorCode: SearchErr(code),
}
if len(eRR) > 0 {
r.Err = eRR[0]
... ... @@ -58,7 +78,7 @@ func (e ErrWithMessage) Unwrap() error {
}
//ParseToMessage 实现CustomErrParse的接口
func (e ErrWithMessage) ParseToMessage() interface{} {
func (e ErrWithMessage) ParseToMessage() *ResponseMessage {
return &ResponseMessage{
ErrorCode: e.ErrorCode,
Data: nil,
... ...
package protocol
import (
"encoding/json"
"testing"
)
func Test_Err(t *testing.T) {
errmsg := NewMesage(0)
bt1, _ := json.Marshal(errmsg)
t.Log(string(bt1))
normalmsg := NewErrWithMessage(0)
bt2, _ := json.Marshal(normalmsg)
t.Log(string(bt2))
}
... ...
package protocol
//ErrorMap 统一消息错误编码
type ErrorMap map[int]string
//Search 搜索错误描述
func (m ErrorMap) Search(code int) ErrorCode {
if v, ok := m[code]; ok {
return ErrorCode{
Errno: code,
Errmsg: v,
}
}
return ErrorCode{}
}
var errmessge ErrorMap = map[int]string{
1: "系统异常",
101: "clientId或clientSecret无效",
... ... @@ -34,6 +20,23 @@ var errmessge ErrorMap = map[int]string{
4142: "Uuid已存在,请求失败",
}
func SearchErr(code int) ErrorCode {
return errmessge.Search(code)
}
func ReturnResponse(data interface{}, eRR error) *ResponseMessage {
var msg *ResponseMessage
if eRR == nil {
msg = NewMesage(0)
msg.Data = data
return msg
}
// fmt.Println("日志:" + eRR.Error())
if x, ok := eRR.(CustomErrParse); ok {
return x.ParseToMessage()
}
return nil
}
func InitMessageCode() {
// messages := []struct {
// Code int
... ...