package errm import ( "fmt" "go-micro.dev/v4/errors" "gomicro-base/common/validate" ) type code int32 const ( DefaultErrorCode int32 = 1000 ParamsErrorCode = 1001 NotFoundErrorCode = 1002 ) var codeStatusText = map[int32]string{ DefaultErrorCode: "操作失败", ParamsErrorCode: "参数不正确", NotFoundErrorCode: "未查询到记录", } type ResponseError struct { Code int `json:"code"` Msg string `json:"msg"` } var _ error = &ResponseError{} // 实现error接口 func (c *ResponseError) Error() string { return fmt.Sprintf("[%d]%s", c.Code, c.Msg) } // NewMicroError 构造go-micro错误响应 func NewMicroError(detail string, code ...int32) error { var c = DefaultErrorCode if len(code) > 0 { c = code[0] } return &errors.Error{ Code: c, Detail: detail, Status: codeStatusText[c], } } // TransParamsError 翻译go-validate验证错误信息 func TransParamsError(err error) error { return NewMicroError(validate.TransError(err), ParamsErrorCode) } // NotFound 未找到错误 func NotFound(detail string) error { return NewMicroError(detail, NotFoundErrorCode) }