-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgrpc.go
More file actions
100 lines (91 loc) · 2.16 KB
/
grpc.go
File metadata and controls
100 lines (91 loc) · 2.16 KB
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
package errors
import (
"google.golang.org/grpc/codes"
)
func grpcStatusCode(eT errType) codes.Code {
status := codes.Unknown
switch eT {
case TypeInternal:
{
status = codes.Internal
}
case TypeValidation, TypeInputBody:
{
status = codes.InvalidArgument
}
case TypeDuplicate:
{
status = codes.AlreadyExists
}
case TypeUnauthenticated:
{
status = codes.Unauthenticated
}
case TypeUnauthorized:
{
status = codes.PermissionDenied
}
case TypeEmpty, TypeNotFound:
{
status = codes.NotFound
}
case TypeMaximumAttempts:
{
status = codes.ResourceExhausted
}
case TypeSubscriptionExpired:
{
status = codes.Unavailable
}
case TypeNotImplemented:
{
status = codes.Unimplemented
}
case TypeContextTimedout, TypeDownstreamDependencyTimedout:
{
status = codes.DeadlineExceeded
}
case TypeContextCancelled:
{
status = codes.Canceled
}
}
return status
}
// GRPCStatusCodeMessage returns the appropriate GRPC status code, message, boolean for the error
// the boolean value is true if the error was of type *Error, false otherwise.
func GRPCStatusCodeMessage(err error) (codes.Code, string, bool) {
code, isErr := GRPCStatusCode(err)
msg, isErrMsg := Message(err)
if msg == "" {
msg = err.Error()
}
return code, msg, isErr && isErrMsg
}
// GRPCStatusCode returns appropriate GRPC response status code based on type of the error. The boolean
// is 'true' if the provided error is of type *Err. If joined error, boolean is true if all joined errors
// are of type *Error
// In case of joined errors, it'll return the status code of the last *Error
func GRPCStatusCode(err error) (codes.Code, bool) {
derr, _ := err.(*Error)
if derr != nil {
return grpcStatusCode(derr.Type()), true
}
// Since TypeInternal is the default returned by getErrType, it is ignored.
if et := getErrType(err); et != TypeInternal {
return grpcStatusCode(et), false
}
jerr, _ := err.(*joinError)
if jerr != nil {
elen := len(jerr.errs)
isErr := true
for i := elen - 1; i >= 0; i-- {
code, isE := GRPCStatusCode(jerr.errs[i])
isErr = isE && isErr
if isE {
return code, isErr
}
}
}
return codes.Unknown, false
}