errors.go 3.9 KB

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