-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodes.go
63 lines (55 loc) · 1.6 KB
/
codes.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
package codes
import (
"errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
ErrCodeNone = 0 // none
ErrCodeCircuitBreak = 3001 // circuit breaked
ErrCodeClientConnNotEstablished = 3100 // client grpc connection not established
ErrCodeClientInvokeTimeout = 3111 // client request timeout
ErrCodeUndefined = 4000 // some errors not defined
ErrCodeRateLimited = 4001 // ratelimit
)
var (
ErrClientConnNotEstablished = WrapCodeFromError(errors.New("client conn not established yet"), ErrCodeClientConnNotEstablished)
ErrClientCircuitBreaked = WrapCodeFromError(errors.New("circuit broken"), ErrCodeCircuitBreak)
ErrClientRequestTimeout = WrapCodeFromError(errors.New("client request timeout"), ErrCodeClientInvokeTimeout)
)
func GetCodeFromError(err error) int {
if err == nil {
return 0
}
st, ok := status.FromError(err)
if !ok {
return ErrCodeUndefined
}
return int(st.Code())
}
func GetCodeAndMessageFromError(err error) (int, string) {
if err == nil {
return 0, ""
}
st, ok := status.FromError(err)
if !ok {
return ErrCodeUndefined, "undefined error:" + err.Error()
}
return int(st.Code()), st.Message()
}
func GetRPCCodeAndMessageFromError(err error) (codes.Code, string) {
if err == nil {
return 0, ""
}
st, ok := status.FromError(err)
if !ok {
return ErrCodeUndefined, "undefined error:" + err.Error()
}
return st.Code(), st.Message()
}
func WrapCodeFromError(err error, code int) error {
if err == nil {
return nil
}
return status.Error(codes.Code(code), err.Error())
}