How to handle error in go grpc service?


(Root Zhang) #1

say we have several grpc services written in go, like

service 1

func (s *srv1) Foo(req Request, rsp *Response) error {
    // handle logic but find some error
    return err
}

service2

func (s *srv2) Bar(req Request, rsp *Response) error {
    // handle logic but find some error
    rsp.Code = Err_Code
    rsp.Msg = err.Error()
    return nil
}

service3

func (s *srv3) Biz(req Request, rsp *Response) error {
    // handle logic and find no error
    return nil
}

and here we have a java client calling our go services:

try {
    srv1.Foo()
    srv2.Bar()
    srv3.Biz()
} catch (Exception e) {
   // handle exception
}

In our case, if srv1 returns error an exception will be caught which cause srv2 and srv3 not being called. So my question is, should our service return error which cause the clients terminated, or should our service always return nil but give rsp.Code and rsp.Msg instead which enable the clients to call srv2 and srv3 even if srv1 failed ? or there are some better ways for the server and client to handle errors?

sorry for my english, thanks for helping :slight_smile:


(Ignacio Gómez) #2

For starters, this has nothing to do with Go but with gRPC, so I don’t think it’s the best place to be discussing it. Anyway, my 2 cents:

That’s because you’re throwing everything inside the same try, which isn’t necessary. If you think you can go on calling next services after one failed, then handle each one separately. It’s not that "rsp.Code and rsp.Msg instead … enable the clients to call srv2 and srv3 even if srv1 failed", is how you handle the errors that enables the subsequent calls: if you actually got an Err_Code from srv1 (with a nil error), how would you handle it and would you continue to call the other services? That’s logic that depends on your application.

On the other hand, what’s the point of having a function return an error if you’ll always return nil?

For what is worth, I would return errors from the services and then handle them properly at the client.


(Root Zhang) #3

thanks, agree with you, but temporarily our team choose to always return nil and use code+msg instead :pensive: maybe someday find a better solution…