-
Notifications
You must be signed in to change notification settings - Fork 180
/
grpc.go
88 lines (75 loc) · 1.71 KB
/
grpc.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
package errors
import (
"net/http"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/pydio/cells/v4/common/proto/service"
)
// CodeFromHTTPStatus converts an HTTP response status into the corresponding
// gRPC error code.
func CodeFromHTTPStatus(status int) codes.Code {
switch status {
case http.StatusOK:
return codes.OK
case http.StatusTooManyRequests:
return codes.ResourceExhausted
case http.StatusRequestTimeout:
return codes.DeadlineExceeded
case http.StatusInternalServerError:
return codes.Unknown
case http.StatusBadRequest:
return codes.InvalidArgument
case http.StatusNotFound:
return codes.NotFound
case http.StatusConflict:
return codes.AlreadyExists
case http.StatusForbidden:
return codes.PermissionDenied
case http.StatusUnauthorized:
return codes.Unauthenticated
case http.StatusPreconditionFailed:
return codes.FailedPrecondition
case http.StatusNotImplemented:
return codes.Unimplemented
case http.StatusServiceUnavailable:
return codes.Unavailable
default:
return codes.Unknown
}
}
func ToGRPC(er error) error {
if er == nil {
return nil
}
err := FromError(er)
s, serr := status.New(CodeFromHTTPStatus(int(err.Code)), err.Detail).WithDetails(&pb.Error{
ID: err.Id,
Code: uint32(err.Code),
Status: err.Status,
Details: err.Detail,
})
if serr != nil {
return serr
}
return s.Err()
}
func FromGRPC(er error) error {
if er == nil {
return nil
}
s, ok := status.FromError(er)
if !ok {
return er
}
details := s.Details()
for _, detail := range details {
err := detail.(*pb.Error)
return &Error{
Id: err.ID,
Code: int32(err.Code),
Status: err.Status,
Detail: err.Details,
}
}
return er
}