go - 如何在 grpc 的状态错误对象的详细信息中发送自定义 proto

标签 go grpc grpc-go

我正在尝试在我的 grpc 调用的错误响应中发送自定义原型(prototype)。根据 this ,应该是可以的。

这是代码。

    st := status.Newf(codes.NotFound, "user %s doesn't exist", req.Name)
    desc := "The username Doesn't exist, please give a valid username"

    customProtoError := &data.Error{
        Message:         "Check username",
        Code:            1404,
        Type:            "Service",
        DetailedMessage: desc,
    }

    st, err := st.WithDetails(customProtoError)
    if err != nil {
        panic(fmt.Sprintf("Unexpected error attaching metadata: %v", err))
    }

我有这些 GRPC API 的 grpc 和 http 处理程序。
HTTP 服务器中使用的 Marshaler 是 github.com/gogo/gateway
mux := runtime.NewServeMux(
    runtime.WithMarshalerOption(JSONContentType, &gateway.JSONPb{}))

HTTP 的配置和 GRPC服务器在这里可用。
当我尝试使用 HTTP 调用访问 API 时,这是我得到的响应。

HTTP 错误:
{
    "error": "user kishore1 doesn't exist",
    "code": 5,
    "message": "user kishore1 doesn't exist",
    "details": [
        {
            "type_url": "type.googleapis.com/data.Error",
            "value": "Cg5DaGVjayB1c2VybmFtZRD8ChoHU2t5ZmxvdyI4VGhlIHVzZXJuYW1lIERvZXNuJ3QgZXhpc3QsIHBsZWFzZSBnaXZlIGEgdmFsaWQgdXNlcm5hbWU="
        }
    ]
}
type_url与 google 一起提供,因为它在 golang proto code 中硬编码.但是this says Any在 JSON 中将被反序列化为嵌入的消息。

Grpc客户端代码:
resp, err := client.GetUser(ctx, req)
        if err != nil {
        st := status.Convert(err)
        for _, detail := range st.Details() {
            switch t := detail.(type) {
            case *pb.Error:
                fmt.Println("Oops! Your request was rejected by the server.")
                ...
            default:
                fmt.Println("Error Received - ", detail, reflect.TypeOf(detail))
            }
        }

Grpc 错误:
Error Received - proto: not found *errors.prefixError

知道是什么导致了这种困惑吗? HTTP 不会反序列化为嵌入式消息,GRPC 会给出 proto.NotFound
这可能是因为 gogo proto 是网关吗?我什至对 googleapis proto errdetails.BadRequest 进行了同样的尝试但还是一样。

最佳答案

花了大约一天后,我才发现问题是由于版本不兼容造成的。
因此,在使用 gogo proto 时,这对我有用。

对于 GRPC 错误,我必须升级我的 grpc-gateway 版本并使用 gogo/status而不是 grpc/status

github.com/gogo/status v1.1.0
github.com/grpc-ecosystem/grpc-gateway v1.14.5

对于 HTTP 错误,我不得不降级我的 golang/protobuf
github.com/golang/protobuf v1.3.2

关于go - 如何在 grpc 的状态错误对象的详细信息中发送自定义 proto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61798483/

相关文章:

JSON 响应 : return nested JSON

http - 在不进行大量分配的情况下在 io.ReadCloser 中查找字符串

go - gRPC 实现性能 - java v/s goLang

go - 将内部 go struct 数组转换为 protobuf 生成的指针数组

go - 在 C 共享库中公开一个带有 2D slice 作为参数的函数(通过 JNA 和 C 在 Java 中使用)

bash - 如何使用 Go 获取 shell 脚本?

java - 尝试将 hyperledger Fabric SDK 与 Spring REST Controller 集成时出现以下错误

c++ - 在 C++ 中将 Gstreamer 与 Google 语音 API(流式转录)结合使用

go - 如何正确运行 evans(gRPC 客户端)?

go - gRPC 客户端流控制如何在 go 中工作?