doumengwei0138
2018-10-24 12:38
浏览 1.1k
已采纳

如何在Go中声明gRPC错误代码客户端

Given the following gRPC server side code:

import (
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
    ....
)

....

func (s *Router) Assign(ctx context.Context, req *api.Request(*api.Response, error) {

    return nil, status.Errorf(codes.PermissionDenied,
}

....

What is the recommended technique for asserting client side that the error is of code = codes.PermissionDenied ?

图片转代码服务由CSDN问答提供 功能建议

给出以下gRPC服务器端代码:

  import(  
“ google.golang.org/grpc/codes"
” google.golang.org/grpc/status"
 .... 
)
 
 .... 
 
func(s * 路由器)Assign(ctx context.Context,req * api.Request(* api.Response,error){
 
返回nil,status.Errorf(codes.PermissionDenied,
} 
 
 .... \  n   
 
 

用于断言客户端错误是否为code = codes.PermissionDenied 的推荐技术是什么? < / DIV>

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongpa2000 2018-10-24 15:36
    已采纳

    Let's say your server returns codes.PermissionDenined like this

    ...
    return nil, status.Error(codes.PermissionDenied, "PERMISSION_DENIED_TEXT")
    

    If your client is Golang as well can also use the status library function FromError to parse the error. I use a switch to determine the error code returned like so

    // client
        assignvar, err := s.MyFunctionCall(ctx, ...)
        if err != nil {
            if e, ok := status.FromError(err); ok {
                switch e.Code() {
                case codes.PermissionDenied:
                    fmt.Println(e.Message()) // this will print PERMISSION_DENIED_TEST
                case codes.Internal:
                    fmt.Println("Has Internal Error")
                case codes.Aborted:
                    fmt.Println("gRPC Aborted the call")
                default:
                    fmt.Println(e.Code(), e.Message())
                }
            }
            else {
                fmt.Printf("not able to parse error returned %v", err)
            }
        }
    
    点赞 评论

相关推荐 更多相似问题