status.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /*
  2. *
  3. * Copyright 2017 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package status implements errors returned by gRPC. These errors are
  19. // serialized and transmitted on the wire between server and client, and allow
  20. // for additional data to be transmitted via the Details field in the status
  21. // proto. gRPC service handlers should return an error created by this
  22. // package, and gRPC clients should expect a corresponding error to be
  23. // returned from the RPC call.
  24. //
  25. // This package upholds the invariants that a non-nil error may not
  26. // contain an OK code, and an OK code must result in a nil error.
  27. package status
  28. import (
  29. "context"
  30. "errors"
  31. "fmt"
  32. "github.com/golang/protobuf/proto"
  33. "github.com/golang/protobuf/ptypes"
  34. spb "google.golang.org/genproto/googleapis/rpc/status"
  35. "google.golang.org/grpc/codes"
  36. "google.golang.org/grpc/internal"
  37. )
  38. func init() {
  39. internal.StatusRawProto = statusRawProto
  40. }
  41. func statusRawProto(s *Status) *spb.Status { return s.s }
  42. // statusError is an alias of a status proto. It implements error and Status,
  43. // and a nil statusError should never be returned by this package.
  44. type statusError spb.Status
  45. func (se *statusError) Error() string {
  46. p := (*spb.Status)(se)
  47. return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(p.GetCode()), p.GetMessage())
  48. }
  49. func (se *statusError) GRPCStatus() *Status {
  50. return &Status{s: (*spb.Status)(se)}
  51. }
  52. // Is implements future error.Is functionality.
  53. // A statusError is equivalent if the code and message are identical.
  54. func (se *statusError) Is(target error) bool {
  55. tse, ok := target.(*statusError)
  56. if !ok {
  57. return false
  58. }
  59. return proto.Equal((*spb.Status)(se), (*spb.Status)(tse))
  60. }
  61. // Status represents an RPC status code, message, and details. It is immutable
  62. // and should be created with New, Newf, or FromProto.
  63. type Status struct {
  64. s *spb.Status
  65. }
  66. // Code returns the status code contained in s.
  67. func (s *Status) Code() codes.Code {
  68. if s == nil || s.s == nil {
  69. return codes.OK
  70. }
  71. return codes.Code(s.s.Code)
  72. }
  73. // Message returns the message contained in s.
  74. func (s *Status) Message() string {
  75. if s == nil || s.s == nil {
  76. return ""
  77. }
  78. return s.s.Message
  79. }
  80. // Proto returns s's status as an spb.Status proto message.
  81. func (s *Status) Proto() *spb.Status {
  82. if s == nil {
  83. return nil
  84. }
  85. return proto.Clone(s.s).(*spb.Status)
  86. }
  87. // Err returns an immutable error representing s; returns nil if s.Code() is
  88. // OK.
  89. func (s *Status) Err() error {
  90. if s.Code() == codes.OK {
  91. return nil
  92. }
  93. return (*statusError)(s.s)
  94. }
  95. // New returns a Status representing c and msg.
  96. func New(c codes.Code, msg string) *Status {
  97. return &Status{s: &spb.Status{Code: int32(c), Message: msg}}
  98. }
  99. // Newf returns New(c, fmt.Sprintf(format, a...)).
  100. func Newf(c codes.Code, format string, a ...interface{}) *Status {
  101. return New(c, fmt.Sprintf(format, a...))
  102. }
  103. // Error returns an error representing c and msg. If c is OK, returns nil.
  104. func Error(c codes.Code, msg string) error {
  105. return New(c, msg).Err()
  106. }
  107. // Errorf returns Error(c, fmt.Sprintf(format, a...)).
  108. func Errorf(c codes.Code, format string, a ...interface{}) error {
  109. return Error(c, fmt.Sprintf(format, a...))
  110. }
  111. // ErrorProto returns an error representing s. If s.Code is OK, returns nil.
  112. func ErrorProto(s *spb.Status) error {
  113. return FromProto(s).Err()
  114. }
  115. // FromProto returns a Status representing s.
  116. func FromProto(s *spb.Status) *Status {
  117. return &Status{s: proto.Clone(s).(*spb.Status)}
  118. }
  119. // FromError returns a Status representing err if it was produced from this
  120. // package or has a method `GRPCStatus() *Status`. Otherwise, ok is false and a
  121. // Status is returned with codes.Unknown and the original error message.
  122. func FromError(err error) (s *Status, ok bool) {
  123. if err == nil {
  124. return nil, true
  125. }
  126. if se, ok := err.(interface {
  127. GRPCStatus() *Status
  128. }); ok {
  129. return se.GRPCStatus(), true
  130. }
  131. return New(codes.Unknown, err.Error()), false
  132. }
  133. // Convert is a convenience function which removes the need to handle the
  134. // boolean return value from FromError.
  135. func Convert(err error) *Status {
  136. s, _ := FromError(err)
  137. return s
  138. }
  139. // WithDetails returns a new status with the provided details messages appended to the status.
  140. // If any errors are encountered, it returns nil and the first error encountered.
  141. func (s *Status) WithDetails(details ...proto.Message) (*Status, error) {
  142. if s.Code() == codes.OK {
  143. return nil, errors.New("no error details for status with code OK")
  144. }
  145. // s.Code() != OK implies that s.Proto() != nil.
  146. p := s.Proto()
  147. for _, detail := range details {
  148. any, err := ptypes.MarshalAny(detail)
  149. if err != nil {
  150. return nil, err
  151. }
  152. p.Details = append(p.Details, any)
  153. }
  154. return &Status{s: p}, nil
  155. }
  156. // Details returns a slice of details messages attached to the status.
  157. // If a detail cannot be decoded, the error is returned in place of the detail.
  158. func (s *Status) Details() []interface{} {
  159. if s == nil || s.s == nil {
  160. return nil
  161. }
  162. details := make([]interface{}, 0, len(s.s.Details))
  163. for _, any := range s.s.Details {
  164. detail := &ptypes.DynamicAny{}
  165. if err := ptypes.UnmarshalAny(any, detail); err != nil {
  166. details = append(details, err)
  167. continue
  168. }
  169. details = append(details, detail.Message)
  170. }
  171. return details
  172. }
  173. // Code returns the Code of the error if it is a Status error, codes.OK if err
  174. // is nil, or codes.Unknown otherwise.
  175. func Code(err error) codes.Code {
  176. // Don't use FromError to avoid allocation of OK status.
  177. if err == nil {
  178. return codes.OK
  179. }
  180. if se, ok := err.(interface {
  181. GRPCStatus() *Status
  182. }); ok {
  183. return se.GRPCStatus().Code()
  184. }
  185. return codes.Unknown
  186. }
  187. // FromContextError converts a context error into a Status. It returns a
  188. // Status with codes.OK if err is nil, or a Status with codes.Unknown if err is
  189. // non-nil and not a context error.
  190. func FromContextError(err error) *Status {
  191. switch err {
  192. case nil:
  193. return nil
  194. case context.DeadlineExceeded:
  195. return New(codes.DeadlineExceeded, err.Error())
  196. case context.Canceled:
  197. return New(codes.Canceled, err.Error())
  198. default:
  199. return New(codes.Unknown, err.Error())
  200. }
  201. }