-
Notifications
You must be signed in to change notification settings - Fork 3
/
errors.go
103 lines (81 loc) · 2.41 KB
/
errors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package errors
import (
"fmt"
"github.com/learninto/goutil/twirp"
"github.com/pkg/errors"
)
// NotLoginError 错误未登录
var NotLoginError = twirp.NewError(twirp.Unauthenticated, "must login")
// PermissionDeniedError 权限不够
var PermissionDeniedError = twirp.NewError(twirp.PermissionDenied, "permission denied")
// token过期
var TokenExpired error = twirp.NewError(twirp.DeadlineExceeded, "Token is expired")
// token未激活
var TokenNotValidYet error = twirp.NewError(twirp.InvalidArgument, "Token not active yet")
// 不是token
var TokenMalformed error = twirp.NewError(twirp.InvalidArgument, "That's not even a token")
// 无法处理token
var TokenInvalid error = twirp.NewError(twirp.InvalidArgument, "Couldn't handle this token:")
// Wrap 包装错误信息,附加调用栈
// 第二个参数只能是 string,也可以不传,大部分情况不用传
func Wrap(err error, args ...interface{}) error {
if len(args) >= 1 {
if msg, ok := args[0].(string); ok {
return errors.Wrap(err, msg)
}
}
return errors.Wrap(err, "")
}
// Cause 获取原始错误对象
func Cause(err error) error {
return errors.Cause(err)
}
// Errorf 创建新错误
func Errorf(format string, args ...interface{}) error {
return errors.Errorf(format, args...)
}
// InvalidArgumentError 参数错误,400
func InvalidArgumentError(argument string, validationMsg string) error {
return twirp.InvalidArgumentError(argument, validationMsg)
}
type codeError struct {
code int32
err string
}
func (c codeError) Error() string {
return c.err
}
// CodeError 新建业务错误,附带错误码
func CodeError(code int32, err string) error {
return codeError{code: code, err: err}
}
// Code 提取错误码,codeError 返回 code 和 true,其他返回 0 和 false
func Code(err error) (int32, bool) {
err = errors.Cause(err)
if err == nil {
return 0, false
}
if ce, ok := err.(codeError); ok {
return ce.code, true
}
return 0, false
}
// MetaError 新建meta错误
//
// 为了避免与httpStatus错误冲突,错误码及错误信息将放在meta中。
// 返回 httpStatus 为 200。
// 返回案例如下:
// {
// "code": "",
// "msg": "",
// "meta": {
// "code": "@code",
// "msg": "@err"
// }
// }
func MetaError(code int32, err string) twirp.Error {
ne := twirp.NewError(twirp.NoError, "")
ne = ne.WithMeta("code", fmt.Sprintf("%v", code))
ne = ne.WithMeta("msg", err)
return ne
}