包状态实现由gRPC返回的错误。这些错误被序列化,并通过服务器和客户机之间的连线传输,并且允许通过状态原型中的Details字段传输其他数据。gRPC服务处理程序应该返回此包创建的错误,而gRPC客户机应该期望从RPC调用返回相应的错误。
常用于客户端解析服务端返回的错误信息

func Code(err error) codes.Code 如果是状态错误,则返回错误的代码
func Error(c codes.Code, msg string) error 返回一个表示c和msg的错误。如果c是OK,返回nil
func Errorf(c codes.Code, format string, a …interface{}) error 返回一个表示s的错误。如果c是OK,返回nil

type Status

func Convert(err error) Status 将服务端返回的错误转换为状态
func FromError(err error) (s
Status, ok bool) 将服务端返回的错误转换为状态
func New(c codes.Code, msg string) Status 新建一个代表c和msg的状态
func Newf(c codes.Code, format string, a …interface{})
Status 新建一个代表c和msg的状态
func (s Status) Code() codes.Code 该状态的code
func (s
Status) Err() error 该状态的err
func (s *Status) Message() string 该状态的消息

举例:

  1. // UnaryServerInterceptor returns a new unary server interceptors that performs request rate limiting.
  2. func UnaryServerInterceptor(limiter Limiter) grpc.UnaryServerInterceptor {
  3. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  4. if limiter.Limit() {
  5. return nil, status.Errorf(codes.ResourceExhausted, "%s is rejected by grpc_ratelimit middleware, please retry later.", info.FullMethod)
  6. }
  7. return handler(ctx, req)
  8. }
  9. }