errors.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. package runtime
  2. import (
  3. "io"
  4. "net/http"
  5. "context"
  6. "github.com/golang/protobuf/proto"
  7. "github.com/golang/protobuf/ptypes"
  8. "github.com/golang/protobuf/ptypes/any"
  9. "google.golang.org/grpc/codes"
  10. "google.golang.org/grpc/grpclog"
  11. "google.golang.org/grpc/status"
  12. )
  13. // HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status.
  14. // See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  15. func HTTPStatusFromCode(code codes.Code) int {
  16. switch code {
  17. case codes.OK:
  18. return http.StatusOK
  19. case codes.Canceled:
  20. return http.StatusRequestTimeout
  21. case codes.Unknown:
  22. return http.StatusInternalServerError
  23. case codes.InvalidArgument:
  24. return http.StatusBadRequest
  25. case codes.DeadlineExceeded:
  26. return http.StatusGatewayTimeout
  27. case codes.NotFound:
  28. return http.StatusNotFound
  29. case codes.AlreadyExists:
  30. return http.StatusConflict
  31. case codes.PermissionDenied:
  32. return http.StatusForbidden
  33. case codes.Unauthenticated:
  34. return http.StatusUnauthorized
  35. case codes.ResourceExhausted:
  36. return http.StatusTooManyRequests
  37. case codes.FailedPrecondition:
  38. return http.StatusBadRequest
  39. case codes.Aborted:
  40. return http.StatusConflict
  41. case codes.OutOfRange:
  42. return http.StatusBadRequest
  43. case codes.Unimplemented:
  44. return http.StatusNotImplemented
  45. case codes.Internal:
  46. return http.StatusInternalServerError
  47. case codes.Unavailable:
  48. return http.StatusServiceUnavailable
  49. case codes.DataLoss:
  50. return http.StatusInternalServerError
  51. }
  52. grpclog.Printf("Unknown gRPC error code: %v", code)
  53. return http.StatusInternalServerError
  54. }
  55. var (
  56. // HTTPError replies to the request with the error.
  57. // You can set a custom function to this variable to customize error format.
  58. HTTPError = DefaultHTTPError
  59. // OtherErrorHandler handles the following error used by the gateway: StatusMethodNotAllowed StatusNotFound and StatusBadRequest
  60. OtherErrorHandler = DefaultOtherErrorHandler
  61. )
  62. type errorBody struct {
  63. Error string `protobuf:"bytes,1,name=error" json:"error"`
  64. Code int32 `protobuf:"varint,2,name=code" json:"code"`
  65. Details []*any.Any `protobuf:"bytes,3,rep,name=details" json:"details,omitempty"`
  66. }
  67. // Make this also conform to proto.Message for builtin JSONPb Marshaler
  68. func (e *errorBody) Reset() { *e = errorBody{} }
  69. func (e *errorBody) String() string { return proto.CompactTextString(e) }
  70. func (*errorBody) ProtoMessage() {}
  71. // DefaultHTTPError is the default implementation of HTTPError.
  72. // If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode.
  73. // If otherwise, it replies with http.StatusInternalServerError.
  74. //
  75. // The response body returned by this function is a JSON object,
  76. // which contains a member whose key is "error" and whose value is err.Error().
  77. func DefaultHTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, _ *http.Request, err error) {
  78. const fallback = `{"error": "failed to marshal error message"}`
  79. w.Header().Del("Trailer")
  80. w.Header().Set("Content-Type", marshaler.ContentType())
  81. s, ok := status.FromError(err)
  82. if !ok {
  83. s = status.New(codes.Unknown, err.Error())
  84. }
  85. body := &errorBody{
  86. Error: s.Message(),
  87. Code: int32(s.Code()),
  88. }
  89. for _, detail := range s.Details() {
  90. if det, ok := detail.(proto.Message); ok {
  91. a, err := ptypes.MarshalAny(det)
  92. if err != nil {
  93. grpclog.Printf("Failed to marshal any: %v", err)
  94. } else {
  95. body.Details = append(body.Details, a)
  96. }
  97. }
  98. }
  99. buf, merr := marshaler.Marshal(body)
  100. if merr != nil {
  101. grpclog.Printf("Failed to marshal error message %q: %v", body, merr)
  102. w.WriteHeader(http.StatusInternalServerError)
  103. if _, err := io.WriteString(w, fallback); err != nil {
  104. grpclog.Printf("Failed to write response: %v", err)
  105. }
  106. return
  107. }
  108. md, ok := ServerMetadataFromContext(ctx)
  109. if !ok {
  110. grpclog.Printf("Failed to extract ServerMetadata from context")
  111. }
  112. handleForwardResponseServerMetadata(w, mux, md)
  113. handleForwardResponseTrailerHeader(w, md)
  114. st := HTTPStatusFromCode(s.Code())
  115. w.WriteHeader(st)
  116. if _, err := w.Write(buf); err != nil {
  117. grpclog.Printf("Failed to write response: %v", err)
  118. }
  119. handleForwardResponseTrailer(w, md)
  120. }
  121. // DefaultOtherErrorHandler is the default implementation of OtherErrorHandler.
  122. // It simply writes a string representation of the given error into "w".
  123. func DefaultOtherErrorHandler(w http.ResponseWriter, _ *http.Request, msg string, code int) {
  124. http.Error(w, msg, code)
  125. }