【问题标题】:returning the grpc status code in case of success在成功的情况下返回 grpc 状态码
【发布时间】:2022-10-20 16:00:36
【问题描述】:

我有一个 grpc 处理程序Something(ctx context.Context, request *protocol.Something) (*pb.Test, error)

我返回像return nil, status.Error(codes.InvalidArgument, "something wrong") 这样的错误

在成功的情况下。我总是返回 nil return test, nil,尽管有代码 0。我必须在成功时返回代码吗? return test, status.New(codes.OK, "OK")

【问题讨论】:

    标签: go grpc


    【解决方案1】:

    doc - 返回码0 表示not an error; returned on success.

    Code Number Description
    OK 0 Not an error; returned on success.

    通过return test, nil,错误中的nil表示没有错误,成功则返回OK

        // OK is returned on success.
        OK Code = 0 
    

    正如您在问题中提到的,return test, status.New(codes.OK, "OK"),实际上,status.New() 只是返回Status 而不是error,它可能在函数Something 中失败。

    您可以使用返回errorstatus.Error(codes.OK, "OK")。但是,如果传入codes.OK,则返回nil。这与直接返回nil 的行为相同。

    源代码

    // Error returns an error representing c and msg.  If c is OK, returns nil.
    func Error(c codes.Code, msg string) error {
        return New(c, msg).Err()
    }
    

    【讨论】:

      【解决方案2】:

      不,您不需要这样做 - 成功时无需返回状态码

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-21
        • 2017-07-08
        • 2014-11-22
        相关资源
        最近更新 更多