status.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /*
  2. *
  3. * Copyright 2020 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. "errors"
  30. "fmt"
  31. "github.com/golang/protobuf/proto"
  32. "github.com/golang/protobuf/ptypes"
  33. spb "google.golang.org/genproto/googleapis/rpc/status"
  34. "google.golang.org/grpc/codes"
  35. )
  36. // Status represents an RPC status code, message, and details. It is immutable
  37. // and should be created with New, Newf, or FromProto.
  38. type Status struct {
  39. s *spb.Status
  40. }
  41. // NewWithProto returns a new status including details from statusProto. This
  42. // is meant to be used by the gRPC library only.
  43. func NewWithProto(code codes.Code, message string, statusProto []string) *Status {
  44. if len(statusProto) != 1 {
  45. // No grpc-status-details bin header, or multiple; just ignore.
  46. return &Status{s: &spb.Status{Code: int32(code), Message: message}}
  47. }
  48. st := &spb.Status{}
  49. if err := proto.Unmarshal([]byte(statusProto[0]), st); err != nil {
  50. // Probably not a google.rpc.Status proto; do not provide details.
  51. return &Status{s: &spb.Status{Code: int32(code), Message: message}}
  52. }
  53. if st.Code == int32(code) {
  54. // The codes match between the grpc-status header and the
  55. // grpc-status-details-bin header; use the full details proto.
  56. return &Status{s: st}
  57. }
  58. return &Status{
  59. s: &spb.Status{
  60. Code: int32(codes.Internal),
  61. Message: fmt.Sprintf(
  62. "grpc-status-details-bin mismatch: grpc-status=%v, grpc-message=%q, grpc-status-details-bin=%+v",
  63. code, message, st,
  64. ),
  65. },
  66. }
  67. }
  68. // New returns a Status representing c and msg.
  69. func New(c codes.Code, msg string) *Status {
  70. return &Status{s: &spb.Status{Code: int32(c), Message: msg}}
  71. }
  72. // Newf returns New(c, fmt.Sprintf(format, a...)).
  73. func Newf(c codes.Code, format string, a ...any) *Status {
  74. return New(c, fmt.Sprintf(format, a...))
  75. }
  76. // FromProto returns a Status representing s.
  77. func FromProto(s *spb.Status) *Status {
  78. return &Status{s: proto.Clone(s).(*spb.Status)}
  79. }
  80. // Err returns an error representing c and msg. If c is OK, returns nil.
  81. func Err(c codes.Code, msg string) error {
  82. return New(c, msg).Err()
  83. }
  84. // Errorf returns Error(c, fmt.Sprintf(format, a...)).
  85. func Errorf(c codes.Code, format string, a ...any) error {
  86. return Err(c, fmt.Sprintf(format, a...))
  87. }
  88. // Code returns the status code contained in s.
  89. func (s *Status) Code() codes.Code {
  90. if s == nil || s.s == nil {
  91. return codes.OK
  92. }
  93. return codes.Code(s.s.Code)
  94. }
  95. // Message returns the message contained in s.
  96. func (s *Status) Message() string {
  97. if s == nil || s.s == nil {
  98. return ""
  99. }
  100. return s.s.Message
  101. }
  102. // Proto returns s's status as an spb.Status proto message.
  103. func (s *Status) Proto() *spb.Status {
  104. if s == nil {
  105. return nil
  106. }
  107. return proto.Clone(s.s).(*spb.Status)
  108. }
  109. // Err returns an immutable error representing s; returns nil if s.Code() is OK.
  110. func (s *Status) Err() error {
  111. if s.Code() == codes.OK {
  112. return nil
  113. }
  114. return &Error{s: s}
  115. }
  116. // WithDetails returns a new status with the provided details messages appended to the status.
  117. // If any errors are encountered, it returns nil and the first error encountered.
  118. func (s *Status) WithDetails(details ...proto.Message) (*Status, error) {
  119. if s.Code() == codes.OK {
  120. return nil, errors.New("no error details for status with code OK")
  121. }
  122. // s.Code() != OK implies that s.Proto() != nil.
  123. p := s.Proto()
  124. for _, detail := range details {
  125. any, err := ptypes.MarshalAny(detail)
  126. if err != nil {
  127. return nil, err
  128. }
  129. p.Details = append(p.Details, any)
  130. }
  131. return &Status{s: p}, nil
  132. }
  133. // Details returns a slice of details messages attached to the status.
  134. // If a detail cannot be decoded, the error is returned in place of the detail.
  135. func (s *Status) Details() []any {
  136. if s == nil || s.s == nil {
  137. return nil
  138. }
  139. details := make([]any, 0, len(s.s.Details))
  140. for _, any := range s.s.Details {
  141. detail := &ptypes.DynamicAny{}
  142. if err := ptypes.UnmarshalAny(any, detail); err != nil {
  143. details = append(details, err)
  144. continue
  145. }
  146. details = append(details, detail.Message)
  147. }
  148. return details
  149. }
  150. func (s *Status) String() string {
  151. return fmt.Sprintf("rpc error: code = %s desc = %s", s.Code(), s.Message())
  152. }
  153. // Error wraps a pointer of a status proto. It implements error and Status,
  154. // and a nil *Error should never be returned by this package.
  155. type Error struct {
  156. s *Status
  157. }
  158. func (e *Error) Error() string {
  159. return e.s.String()
  160. }
  161. // GRPCStatus returns the Status represented by se.
  162. func (e *Error) GRPCStatus() *Status {
  163. return e.s
  164. }
  165. // Is implements future error.Is functionality.
  166. // A Error is equivalent if the code and message are identical.
  167. func (e *Error) Is(target error) bool {
  168. tse, ok := target.(*Error)
  169. if !ok {
  170. return false
  171. }
  172. return proto.Equal(e.s.s, tse.s.s)
  173. }
  174. // IsRestrictedControlPlaneCode returns whether the status includes a code
  175. // restricted for control plane usage as defined by gRFC A54.
  176. func IsRestrictedControlPlaneCode(s *Status) bool {
  177. switch s.Code() {
  178. case codes.InvalidArgument, codes.NotFound, codes.AlreadyExists, codes.FailedPrecondition, codes.Aborted, codes.OutOfRange, codes.DataLoss:
  179. return true
  180. }
  181. return false
  182. }