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

如何在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 ?

  • 写回答

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)
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?