在成功的情况下返回gRPC状态码。

huangapple go评论83阅读模式
英文:

returning the grpc status code in case of success

问题

我有一个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")

英文:

I have a grpc handler Something(ctx context.Context, request *protocol.Something) (*pb.Test, error)

I return errors like return nil, status.Error(codes.InvalidArgument, "something wrong")

In case of success. I always return nil return test, nil, although there is code 0. Do I have to return the code on success? return test, status.New(codes.OK, "OK")

答案1

得分: 3

根据文档 - 返回代码0表示没有错误;成功返回

Code Number Description
OK 0 没有错误;成功返回。

通过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函数中可能会失败。

你可以使用status.Error(codes.OK, "OK"),它返回error。然而,如果传入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()
}
英文:

Per doc - return code 0 means not an error; returned on success.

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

Through return test, nil, the nil in the error, means there is no error, and OK is returned on success

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

As you mentioned in the question, return test, status.New(codes.OK, "OK"), actually, the status.New() just return Status rather than error, it could be failed in the function Something.

You may use status.Error(codes.OK, "OK") which return error. However, if codes.OK is passed in, returns nil. It is the same behavior as return nil directly.

Source code

// 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

得分: 0

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

英文:

No you don't need to do that - no need to return the status code ok on success

huangapple
  • 本文由 发表于 2022年10月14日 06:23:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/74062430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定