Exception Handling and Error Propagation in gRPC Java
It is quite important to propagate detailed error information from the server to the client in case something goes wrong, but the gRPC documentation lacks details on this topic.
In this tutorial, we are going to look at how to handle exceptions in the gRPC Java server and provide information about them to clients.
1. Server and Client
To begin, we will create a simple server and client.
We created a simple server and client to it, which sends the request and outputs the response to the console.
Note: on the server, we process requests with a missing name and use World in this case,
and since our client does not include any name in the request, we will see Hello, World! in the output.
2. Exception Handling
Let’s move on to the main issue, exception handling.
2.1 Throw Exception
Now we do not want to accept requests with a missing name, so we update our server to throw exception in this case.
We replace the line:
If we start our server and client, we will see an exception in the server console:
java.lang.IllegalArgumentException: Missing name
We will also see an exception in the client console, but there is no information about what went wrong:
Exception in thread "main" io.grpc.StatusRuntimeException: UNKNOWN
2.2 Handle Exception
Our goal is to provide more detailed information about exceptions on the server to the client.
To do this, we create an interceptor that will catch exceptions and handle them:
Note: in the interceptor, we use a private class that inherits SimpleForwardingServerCallListener,
and overrides onHalfClose and onReady methods to handle exceptions.
There is no point to override onCancel and onComplete, since it is already too late.
Next we need to add an interceptor to the server:
Now, when we start the server and client, we will see a more informative exception in the client console:
Exception in thread "main" io.grpc.StatusRuntimeException: INVALID_ARGUMENT: Missing name
In our example, we handle only IllegalArgumentException, but you can handle any other exceptions in the same way
and also include much more information in the response besides the exception message.