123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162 |
- package status
- import (
- "errors"
- "fmt"
- "github.com/golang/protobuf/proto"
- "github.com/golang/protobuf/ptypes"
- spb "google.golang.org/genproto/googleapis/rpc/status"
- "google.golang.org/grpc/codes"
- )
- type Status struct {
- s *spb.Status
- }
- func New(c codes.Code, msg string) *Status {
- return &Status{s: &spb.Status{Code: int32(c), Message: msg}}
- }
- func Newf(c codes.Code, format string, a ...interface{}) *Status {
- return New(c, fmt.Sprintf(format, a...))
- }
- func FromProto(s *spb.Status) *Status {
- return &Status{s: proto.Clone(s).(*spb.Status)}
- }
- func Err(c codes.Code, msg string) error {
- return New(c, msg).Err()
- }
- func Errorf(c codes.Code, format string, a ...interface{}) error {
- return Err(c, fmt.Sprintf(format, a...))
- }
- func (s *Status) Code() codes.Code {
- if s == nil || s.s == nil {
- return codes.OK
- }
- return codes.Code(s.s.Code)
- }
- func (s *Status) Message() string {
- if s == nil || s.s == nil {
- return ""
- }
- return s.s.Message
- }
- func (s *Status) Proto() *spb.Status {
- if s == nil {
- return nil
- }
- return proto.Clone(s.s).(*spb.Status)
- }
- func (s *Status) Err() error {
- if s.Code() == codes.OK {
- return nil
- }
- return &Error{e: s.Proto()}
- }
- func (s *Status) WithDetails(details ...proto.Message) (*Status, error) {
- if s.Code() == codes.OK {
- return nil, errors.New("no error details for status with code OK")
- }
-
- p := s.Proto()
- for _, detail := range details {
- any, err := ptypes.MarshalAny(detail)
- if err != nil {
- return nil, err
- }
- p.Details = append(p.Details, any)
- }
- return &Status{s: p}, nil
- }
- func (s *Status) Details() []interface{} {
- if s == nil || s.s == nil {
- return nil
- }
- details := make([]interface{}, 0, len(s.s.Details))
- for _, any := range s.s.Details {
- detail := &ptypes.DynamicAny{}
- if err := ptypes.UnmarshalAny(any, detail); err != nil {
- details = append(details, err)
- continue
- }
- details = append(details, detail.Message)
- }
- return details
- }
- type Error struct {
- e *spb.Status
- }
- func (e *Error) Error() string {
- return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(e.e.GetCode()), e.e.GetMessage())
- }
- func (e *Error) GRPCStatus() *Status {
- return FromProto(e.e)
- }
- func (e *Error) Is(target error) bool {
- tse, ok := target.(*Error)
- if !ok {
- return false
- }
- return proto.Equal(e.e, tse.e)
- }
|