status.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. // New returns a Status representing c and msg.
  42. func New(c codes.Code, msg string) *Status {
  43. return &Status{s: &spb.Status{Code: int32(c), Message: msg}}
  44. }
  45. // Newf returns New(c, fmt.Sprintf(format, a...)).
  46. func Newf(c codes.Code, format string, a ...interface{}) *Status {
  47. return New(c, fmt.Sprintf(format, a...))
  48. }
  49. // FromProto returns a Status representing s.
  50. func FromProto(s *spb.Status) *Status {
  51. return &Status{s: proto.Clone(s).(*spb.Status)}
  52. }
  53. // Err returns an error representing c and msg. If c is OK, returns nil.
  54. func Err(c codes.Code, msg string) error {
  55. return New(c, msg).Err()
  56. }
  57. // Errorf returns Error(c, fmt.Sprintf(format, a...)).
  58. func Errorf(c codes.Code, format string, a ...interface{}) error {
  59. return Err(c, fmt.Sprintf(format, a...))
  60. }
  61. // Code returns the status code contained in s.
  62. func (s *Status) Code() codes.Code {
  63. if s == nil || s.s == nil {
  64. return codes.OK
  65. }
  66. return codes.Code(s.s.Code)
  67. }
  68. // Message returns the message contained in s.
  69. func (s *Status) Message() string {
  70. if s == nil || s.s == nil {
  71. return ""
  72. }
  73. return s.s.Message
  74. }
  75. // Proto returns s's status as an spb.Status proto message.
  76. func (s *Status) Proto() *spb.Status {
  77. if s == nil {
  78. return nil
  79. }
  80. return proto.Clone(s.s).(*spb.Status)
  81. }
  82. // Err returns an immutable error representing s; returns nil if s.Code() is OK.
  83. func (s *Status) Err() error {
  84. if s.Code() == codes.OK {
  85. return nil
  86. }
  87. return &Error{s: s}
  88. }
  89. // WithDetails returns a new status with the provided details messages appended to the status.
  90. // If any errors are encountered, it returns nil and the first error encountered.
  91. func (s *Status) WithDetails(details ...proto.Message) (*Status, error) {
  92. if s.Code() == codes.OK {
  93. return nil, errors.New("no error details for status with code OK")
  94. }
  95. // s.Code() != OK implies that s.Proto() != nil.
  96. p := s.Proto()
  97. for _, detail := range details {
  98. any, err := ptypes.MarshalAny(detail)
  99. if err != nil {
  100. return nil, err
  101. }
  102. p.Details = append(p.Details, any)
  103. }
  104. return &Status{s: p}, nil
  105. }
  106. // Details returns a slice of details messages attached to the status.
  107. // If a detail cannot be decoded, the error is returned in place of the detail.
  108. func (s *Status) Details() []interface{} {
  109. if s == nil || s.s == nil {
  110. return nil
  111. }
  112. details := make([]interface{}, 0, len(s.s.Details))
  113. for _, any := range s.s.Details {
  114. detail := &ptypes.DynamicAny{}
  115. if err := ptypes.UnmarshalAny(any, detail); err != nil {
  116. details = append(details, err)
  117. continue
  118. }
  119. details = append(details, detail.Message)
  120. }
  121. return details
  122. }
  123. func (s *Status) String() string {
  124. return fmt.Sprintf("rpc error: code = %s desc = %s", s.Code(), s.Message())
  125. }
  126. // Error wraps a pointer of a status proto. It implements error and Status,
  127. // and a nil *Error should never be returned by this package.
  128. type Error struct {
  129. s *Status
  130. }
  131. func (e *Error) Error() string {
  132. return e.s.String()
  133. }
  134. // GRPCStatus returns the Status represented by se.
  135. func (e *Error) GRPCStatus() *Status {
  136. return e.s
  137. }
  138. // Is implements future error.Is functionality.
  139. // A Error is equivalent if the code and message are identical.
  140. func (e *Error) Is(target error) bool {
  141. tse, ok := target.(*Error)
  142. if !ok {
  143. return false
  144. }
  145. return proto.Equal(e.s.s, tse.s.s)
  146. }
  147. // IsRestrictedControlPlaneCode returns whether the status includes a code
  148. // restricted for control plane usage as defined by gRFC A54.
  149. func IsRestrictedControlPlaneCode(s *Status) bool {
  150. switch s.Code() {
  151. case codes.InvalidArgument, codes.NotFound, codes.AlreadyExists, codes.FailedPrecondition, codes.Aborted, codes.OutOfRange, codes.DataLoss:
  152. return true
  153. }
  154. return false
  155. }