grpc.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package errcode
  2. import (
  3. "net/http"
  4. "google.golang.org/grpc/codes"
  5. "google.golang.org/grpc/status"
  6. )
  7. // CodeFromGrpcError converts the gRPC error to an HTTP status code.
  8. // See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  9. func CodeFromGrpcError(err error) int {
  10. code := status.Code(err)
  11. switch code {
  12. case codes.OK:
  13. return http.StatusOK
  14. case codes.InvalidArgument, codes.FailedPrecondition, codes.OutOfRange:
  15. return http.StatusBadRequest
  16. case codes.Unauthenticated:
  17. return http.StatusUnauthorized
  18. case codes.PermissionDenied:
  19. return http.StatusForbidden
  20. case codes.NotFound:
  21. return http.StatusNotFound
  22. case codes.Canceled:
  23. return http.StatusRequestTimeout
  24. case codes.AlreadyExists, codes.Aborted:
  25. return http.StatusConflict
  26. case codes.ResourceExhausted:
  27. return http.StatusTooManyRequests
  28. case codes.Internal, codes.DataLoss, codes.Unknown:
  29. return http.StatusInternalServerError
  30. case codes.Unimplemented:
  31. return http.StatusNotImplemented
  32. case codes.Unavailable:
  33. return http.StatusServiceUnavailable
  34. case codes.DeadlineExceeded:
  35. return http.StatusGatewayTimeout
  36. }
  37. return http.StatusInternalServerError
  38. }
  39. // IsGrpcError checks if the error is a gRPC error.
  40. func IsGrpcError(err error) bool {
  41. if err == nil {
  42. return false
  43. }
  44. _, ok := err.(interface {
  45. GRPCStatus() *status.Status
  46. })
  47. return ok
  48. }