Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I transfer a detail exception message within gRPC's responseObserver.onError()

Tags:

grpc

grpc-java

I'm trying to transfer a detail message that describe the exception with gRPC. I've learned that I should use responseObserver.onError to transfer it, and gRPC offer Metadata to do it, but I still don't know where to put it because i can't create a Metadata, all the constructor of Metadata is not public.

static class GrpcTestService extends GrpcTestGrpc.GrpcTestImplBase {

        @Override
        public void sayHello(HelloRequest req, StreamObserver<HelloResponse> responseObserver) {
            try {
                HelloResponse reply = HelloResponse.newBuilder().setMessage("got it ! " + req.getName()).build();
                throw new RuntimeException("I'm an exception!!!");
//                responseObserver.onNext(reply);
//                responseObserver.onCompleted();
            } catch (Exception e) {
                responseObserver.onError(new StatusRuntimeException(Status.ABORTED, new Metadata("metadata exception".getBytes())));
            }
        }
    }

As above, I can't create an Metadata by 'new Metadata("xxxx")', so how can I wrap my special message within responseObserver.onError?

like image 817
Long.zhao Avatar asked Sep 17 '25 23:09

Long.zhao


1 Answers

To send a detailed message, attach it to a Status with withDescription:

Status.ABORTED.withDescription("The detailed reason")

The description is useful for developers to debug the system. It is not intended for machine consumption.

The constructor for Metadata is public, but has no arguments. You create it with new Metadata() and then can modify it with things like put(Key<T> key, T value). Metadata is useful for sending machine-understandable error details.

like image 95
Eric Anderson Avatar answered Sep 21 '25 15:09

Eric Anderson