-
Notifications
You must be signed in to change notification settings - Fork 3
/
convert.go
77 lines (69 loc) · 1.88 KB
/
convert.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
package ecodes
import (
"context"
"net/http"
"google.golang.org/grpc/status"
"google.golang.org/grpc/codes"
)
// GrpcToHTTPStatusCode gRPC转HTTP Code
// example:
// spbStatus := status.FromContextError(err)
// httpStatusCode := ecode.GrpcToHTTPStatusCode(spbStatus.Code())
func GrpcToHTTPStatusCode(statusCode codes.Code) int {
switch statusCode {
case codes.OK:
return http.StatusOK
case codes.Canceled:
return http.StatusRequestTimeout
case codes.Unknown:
return http.StatusInternalServerError
case codes.InvalidArgument:
return http.StatusBadRequest
case codes.DeadlineExceeded:
return http.StatusRequestTimeout
case codes.NotFound:
return http.StatusNotFound
case codes.AlreadyExists:
return http.StatusConflict
case codes.PermissionDenied:
return http.StatusForbidden
case codes.Unauthenticated:
return http.StatusUnauthorized
case codes.ResourceExhausted:
return http.StatusServiceUnavailable
case codes.FailedPrecondition:
return http.StatusPreconditionFailed
case codes.Aborted:
return http.StatusConflict
case codes.OutOfRange:
return http.StatusBadRequest
case codes.Unimplemented:
return http.StatusNotImplemented
case codes.Internal:
return http.StatusInternalServerError
case codes.Unavailable:
return http.StatusServiceUnavailable
case codes.DataLoss:
return http.StatusInternalServerError
default:
return http.StatusInternalServerError
}
}
// Convert 内部转换,为了让err=nil的时候,监控数据里有OK信息
func Convert(err error) *status.Status {
if err == nil {
return status.New(codes.OK, "OK")
}
if se, ok := err.(interface {
GRPCStatus() *status.Status
}); ok {
return se.GRPCStatus()
}
switch err {
case context.DeadlineExceeded:
return status.New(codes.DeadlineExceeded, err.Error())
case context.Canceled:
return status.New(codes.Canceled, err.Error())
}
return status.New(codes.Unknown, err.Error())
}