英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论