GRPC Java logging in tests

Bojan Vukasovic :

So, I am using grpc-testin library to make some integration tests. When I use this code:

@Rule
public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();

@Test
public void doTest() throws IOException {
        String serverName = InProcessServerBuilder.generateName();

        grpcCleanup.register(InProcessServerBuilder
                .forName(serverName).directExecutor().addService(service).build().start());

        SomeServerGrpc.SomeServerBlockingStub blockingStub = SomeServerGrpc.newBlockingStub(
                grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));

...

whenever there is an exception in code, I get

io.grpc.StatusRuntimeException: UNKNOWN

    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:233)
    at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:214)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:139)

How to make grpc to return real reason for the exception and not only UNKNOWN?

Bojan Vukasovic :

OK, I finally found a way:

grpcCleanup.register(InProcessServerBuilder.forName(serverName).intercept(si).directExecutor().addService(service).build().start());

and

private ServerInterceptor si = new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            ServerCall<ReqT, RespT> wrappedCall = new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
                @Override
                public void sendMessage(RespT message) {
                    super.sendMessage(message);
                }

                @Override
                public void close(Status status, Metadata trailers) {
                    System.out.println("Interceptor: " + (status.getCause() == null ? "null" : status.getCause().getClass().getName()));
                    if (status.getCode() == Status.Code.UNKNOWN
                            && status.getDescription() == null
                            && status.getCause() != null) {
                        Throwable e = status.getCause();
                        status = Status.INTERNAL
                                .withDescription(e.getMessage())
                                .augmentDescription(stacktraceToString(e));
                    }
                    super.close(status, trailers);
                }
            };

            return next.startCall(wrappedCall, headers);
        }

        private String stacktraceToString(Throwable e) {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            return stringWriter.toString();
        }
    };

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=151936&siteId=1