In gRPC, how do I add a global exception hook that catches any RuntimeException and propagates meaningful information to the client?
for example, the divide method may throw an ArithmeticException with the message / by zero . On the server side, I can write:
@Override public void divide(DivideRequest request, StreamObserver<DivideResponse> responseObserver) { int dom = request.getDenominator(); int num = request.getNumerator(); double result = num / dom; responseObserver.onNext(DivideResponse.newBuilder().setValue(result).build()); responseObserver.onCompleted(); }
If the client passes the denominator = 0, he will receive:
Exception in thread "main" io.grpc.StatusRuntimeException: UNKNOWN
And the server displays
Exception while executing runnable io.grpc.in ternal.ServerImpl$JumpToApplicationThreadServerStreamListener$2@ 62e95ade java.lang.ArithmeticException: / by zero
The client does not know what is happening.
If I want to pass the / by zero message to the client, I need to change the server to: (as described in this question )
try { double result = num / dom; responseObserver.onNext(DivideResponse.newBuilder().setValue(result).build()); responseObserver.onCompleted(); } catch (Exception e) { logger.error("onError : {}" , e.getMessage()); responseObserver.onError(new StatusRuntimeException(Status.INTERNAL.withDescription(e.getMessage()))); }
And if the client sends the denominator = 0, it will receive:
Exception in thread "main" io.grpc.StatusRuntimeException: INTERNAL: / by zero
Good, / by zero is passed to the client.
But the problem is that in a truly corporate environment there will be a lot of RuntimeException , and if I want to pass these exception messages to the client, I will have to try to catch every method, which is very cumbersome.
Is there any global interceptor that intercepts each method, catches a RuntimeException and onError and propagates an error message to the client? So I do not need to deal with a RuntimeException in my server code.
Thanks a lot!
Note:
<grpc.version>1.0.1</grpc.version> com.google.protobuf:proton:3.1.0 io.grpc:protoc-gen-grpc-java:1.0.1