[Ruby] How do I raise a Rich Error from Ruby Server?

40 views
Skip to first unread message

jua...@flexport.com

unread,
Jan 14, 2020, 7:08:24 PM1/14/20
to grpc.io
According to gRPC Error Handing, Richer error model contains much more information than the standard one comes with gRPC default. So I decided to use it for my gRPC servers for Errors.

In Java, I am able to easily use it and return Error in response as 

Status status = Status.newBuilder()
        .setCode(Code.INVALID_ARGUMENT.getNumber())
        .setMessage("Required argument is empty.")
        .addDetails(Any.pack(DebugInfo.newBuilder().addStackEntries("This is a sample stack trace").build()))
        .build();
      responseObserver.onError(StatusProto.toStatusRuntimeException(status));

However, I also have gRPC servers which are written in Ruby. And I can't find a way to raise an exception or return error status as in Java.

I did this:

    debug_info = Google::Rpc::DebugInfo.new(
      stack_entries: ["1", "2"] ,
    )

    error_status = Google::Rpc::Status.new(
      code: 3,
      message: "msg",
      details: [Google::Protobuf::Any.pack(debug_info)]
    )
# no way for me to throw exception from error_status

After i initialized a Google::Rpc::Status instance, it seems like there is no way for me to raise an exception from error_status I created. Anyone has any idea how I can do it in Ruby? Thanks!

Juanyi Feng

unread,
Jan 14, 2020, 11:34:08 PM1/14/20
to grpc.io
Answering my own question - 

I am about to build workaround by doing this:

debug_info_any = Google::Protobuf::Any.pack(
 
Google::Rpc::DebugInfo.new(
 stack_entries
: ["stack_entries 1", "stack_entries 2"],
 
)
)
rich_error
= Google::Rpc::Status.new(
 code
: 1,
 message
: 'matching message',
 details
: [debug_info_any],
 
)
encoded_rich_error
= Google::Rpc::Status.encode(rich_error)
raise GRPC::BadStatus.new(
 GRPC
::Core::StatusCodes::INVALID_ARGUMENT,
 
"invalid argument msg",
 
'grpc-status-details-bin' => encoded_rich_error)

But I still wonder if there's a better approach in Ruby. Thanks!

Alexander Polcyn

unread,
Jan 15, 2020, 1:13:15 PM1/15/20
to grpc.io
Suggest taking a look at this test for usage of the google.rpc.Status protobuf-based richer error model: https://github.com/grpc/grpc/blob/5a419c65b02b069f4c92623678743a3ddddc53cb/src/ruby/spec/google_rpc_status_utils_spec.rb#L182

However, existing support for the richer error model in ruby is focused on client side error extraction. That is, there is a utility
for extracting rich errors on the ruby client side, but there's not a corresponding utility at the server side for sending one.

I.e., your code sample above is currently the best way of sending a rich error from a ruby server. This TODO in the
Reply all
Reply to author
Forward
0 new messages