error.go 1.11 KB
Newer Older
1
package errm
kzkzzzz's avatar
kzkzzzz committed
2 3 4

import (
	"fmt"
kzkzzzz's avatar
kzkzzzz committed
5 6
	"go-micro.dev/v4/errors"
	"gomicro-base/common/validate"
kzkzzzz's avatar
kzkzzzz committed
7 8
)

kzkzzzz's avatar
kzkzzzz committed
9 10
type code int32

kzkzzzz's avatar
kzkzzzz committed
11
const (
kzkzzzz's avatar
kzkzzzz committed
12 13 14
	DefaultErrorCode  int32 = 1000
	ParamsErrorCode         = 1001
	NotFoundErrorCode       = 1002
kzkzzzz's avatar
kzkzzzz committed
15 16
)

kzkzzzz's avatar
kzkzzzz committed
17 18 19 20 21 22
var codeStatusText = map[int32]string{
	DefaultErrorCode:  "操作失败",
	ParamsErrorCode:   "参数不正确",
	NotFoundErrorCode: "未查询到记录",
}

kzkzzzz's avatar
kzkzzzz committed
23 24 25 26 27 28 29
type ResponseError struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

var _ error = &ResponseError{}

30
// 实现error接口
kzkzzzz's avatar
kzkzzzz committed
31 32 33 34
func (c *ResponseError) Error() string {
	return fmt.Sprintf("[%d]%s", c.Code, c.Msg)
}

35
// NewMicroError 构造go-micro错误响应
kzkzzzz's avatar
kzkzzzz committed
36 37
func NewMicroError(detail string, code ...int32) error {
	var c = DefaultErrorCode
kzkzzzz's avatar
kzkzzzz committed
38 39 40
	if len(code) > 0 {
		c = code[0]
	}
kzkzzzz's avatar
kzkzzzz committed
41
	return &errors.Error{
kzkzzzz's avatar
kzkzzzz committed
42
		Code:   c,
kzkzzzz's avatar
kzkzzzz committed
43
		Detail: detail,
kzkzzzz's avatar
kzkzzzz committed
44
		Status: codeStatusText[c],
kzkzzzz's avatar
kzkzzzz committed
45 46 47
	}
}

48
// TransParamsError 翻译go-validate验证错误信息
kzkzzzz's avatar
kzkzzzz committed
49 50 51 52
func TransParamsError(err error) error {
	return NewMicroError(validate.TransError(err), ParamsErrorCode)
}

53
// NotFound 未找到错误
kzkzzzz's avatar
kzkzzzz committed
54 55
func NotFound(detail string) error {
	return NewMicroError(detail, NotFoundErrorCode)
kzkzzzz's avatar
kzkzzzz committed
56
}