forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
55 lines (48 loc) · 1.35 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
package errcode
import (
"net/http"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// CodeFromGrpcError converts the gRPC error to an HTTP status code.
// See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
func CodeFromGrpcError(err error) int {
code := status.Code(err)
switch code {
case codes.OK:
return http.StatusOK
case codes.InvalidArgument, codes.FailedPrecondition, codes.OutOfRange:
return http.StatusBadRequest
case codes.Unauthenticated:
return http.StatusUnauthorized
case codes.PermissionDenied:
return http.StatusForbidden
case codes.NotFound:
return http.StatusNotFound
case codes.Canceled:
return http.StatusRequestTimeout
case codes.AlreadyExists, codes.Aborted:
return http.StatusConflict
case codes.ResourceExhausted:
return http.StatusTooManyRequests
case codes.Internal, codes.DataLoss, codes.Unknown:
return http.StatusInternalServerError
case codes.Unimplemented:
return http.StatusNotImplemented
case codes.Unavailable:
return http.StatusServiceUnavailable
case codes.DeadlineExceeded:
return http.StatusGatewayTimeout
}
return http.StatusInternalServerError
}
// IsGrpcError checks if the error is a gRPC error.
func IsGrpcError(err error) bool {
if err == nil {
return false
}
_, ok := err.(interface {
GRPCStatus() *status.Status
})
return ok
}