errors.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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"
  8. "google.golang.org/grpc/codes"
  9. "google.golang.org/grpc/grpclog"
  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 `json:"error"`
  61. Code int `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, 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. body := &errorBody{
  78. Error: grpc.ErrorDesc(err),
  79. Code: int(grpc.Code(err)),
  80. }
  81. buf, merr := marshaler.Marshal(body)
  82. if merr != nil {
  83. grpclog.Printf("Failed to marshal error message %q: %v", body, merr)
  84. w.WriteHeader(http.StatusInternalServerError)
  85. if _, err := io.WriteString(w, fallback); err != nil {
  86. grpclog.Printf("Failed to write response: %v", err)
  87. }
  88. return
  89. }
  90. md, ok := ServerMetadataFromContext(ctx)
  91. if !ok {
  92. grpclog.Printf("Failed to extract ServerMetadata from context")
  93. }
  94. handleForwardResponseServerMetadata(w, md)
  95. handleForwardResponseTrailerHeader(w, md)
  96. st := HTTPStatusFromCode(grpc.Code(err))
  97. w.WriteHeader(st)
  98. if _, err := w.Write(buf); err != nil {
  99. grpclog.Printf("Failed to write response: %v", err)
  100. }
  101. handleForwardResponseTrailer(w, md)
  102. }
  103. // DefaultOtherErrorHandler is the default implementation of OtherErrorHandler.
  104. // It simply writes a string representation of the given error into "w".
  105. func DefaultOtherErrorHandler(w http.ResponseWriter, _ *http.Request, msg string, code int) {
  106. http.Error(w, msg, code)
  107. }