2

I am working on a grpc service using golang, I observed that if there is an rpc error, I get

response = nil 
err = some error

even if I am returning a non nil response along with error.

However I also see in my pb.go file:

err := c.cc.Invoke(ctx, "/proto.MyService/Hello", in, out, opts...)
    if err != nil {
        return nil, err
    }
    return out, nil

If err is not nil , they make the reponse nil, I guess this is the reason why I am getting such response.

I dont think it makes sense to get response when there is an error but still, Is there a way I can get both non-nil response and err from grpc ?

Aman Patel
  • 79
  • 7
  • There are two types of errors when using something like grpc. Errors returned by your processing code , and errors returned by the grpc subsystem (which should not be ignored). The former is where you can do custom handling by not propagating the error the normal way, instead putting the error information in the response itself. – Marc May 22 '20 at 07:44
  • Thanks @Marc . This is what I am currently doing – Aman Patel May 24 '20 at 13:55

2 Answers2

1

As explained from official documentation, the standard gRPC error is a code and an additional error string.

If you need to get some kind of response, use the rich error model instead to include the response with it. For an example check Pattern for rich error handling in gRPC

Damien Leroux
  • 11,177
  • 7
  • 43
  • 57
1

The reason is simple. gRPC is a specific implementation of the concept of RPC's (Remote Procedure Calls), where another process is called as though it's a part of your system. gRPC cross-compiles to other languages, including onces that do not support multiple return values (e.g. C++, Java). Instead of returning an error, the generated client is going to throw an exception. Any response you return in addition to the error, therefore, is going to get ignored, making your implementation less portable.

While go supports both, we don't want an RPC to yield different results depending on the specific language a client was implemented in. What else is the pb.go file supposed to do, other than: if an error occurred, all information should be in the error, if not, the response should be returned?

Enrich the errors you return, should you still find yourself needing both.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • Thanks @Elias . This really gave a good insight into understanding it better – Aman Patel May 24 '20 at 13:57
  • @AmanPatel No worries. If an answer is helpful, the way to "thank" people is to upvote and or mark an answer as accepted, rather than leaving a thank you comment. Thanks – Elias Van Ootegem May 24 '20 at 14:58