简体   繁体   中英

What's the correct way to return a 'not found' response from a GRPC c++ server implementation?

I'm looking through the guides and documentation, but am not deeply familiar with idiomatic C++ programming. In all the server implementation cases I've seen, the response grpc::Status::OK is returned at the end of an RPC implementation, for example:

(from https://github.com/grpc/grpc/blob/master/examples/cpp/helloworld/greeter_server.cc )

class GreeterServiceImpl final : public Greeter::Service {
  Status SayHello(ServerContext* context, const HelloRequest* request,
                  HelloReply* reply) override {
    std::string prefix("Hello ");
    reply->set_message(prefix + request->name());
    return Status::OK;
  }
};

Is the expected pattern of implementation that Status::OK is always returned? Are there other options that you should return on failure conditions (such as a 404 response to a requested resource not being found)?

Or is it expected that you'll encode the relevant error conditions into your own proto messages, and always reply with a message that possibly contains the error details?

I thought the documentation reflected that there were other status codes that could be returned (NOT_FOUND for example), but when I tried that I'm getting a compilation error:

No member named 'NOT_FOUND' in 'grpc::Status'; did you mean 'grpc::NOT_FOUND'?

And the method doesn't like it if I'm not returning grpc::NOT_FOUND , as it's an incompatible type.

You can return an explicitly generated status by creating a Status() with a code and message, for example:

return grpc::Status(grpc::StatusCode::NOT_FOUND, "error details here");

and return that instead of Status::OK to send an error message;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM