Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot gRPC: How to return error code when business error happens?

I am implementing a gRPC API using LogNet grpc-spring-boot-starter.

I want to return, for instance, an INVALID_ARGUMENT error code when an incorrect argument has been passed.

If I throw a custom exception it ends up with io.grpc.StatusRuntimeException: UNKNOWN.

Q: Is it possible to define some exception handling mechanism so that exceptions of a particular type will always lead to correct gRPC statuses?

There is unfortunately not so much documentation in the project.

like image 251
Sasha Shpota Avatar asked Jul 05 '19 13:07

Sasha Shpota


1 Answers

gRPC discourages you from throwing an exception in order to communicate that error to the user. This is because it is trivial to accidentally leak information that you may not have considered being sent to a client.

Instead, you are encouraged to pass a StatusException or StatusRuntimeException to streamObserver.onError(Throwable). If you are using exceptions to communicate this information within your own code, you can put a try-catch within your code and pass the exception to onError(). For example, this might be fair for StatusException, since it is a checked exception.

There is the TransmitStatusRuntimeExceptionInterceptor which will catch exceptions during callbacks and if it is a StatusRuntimeException, close the call with the exception's status. This matches closely to what you're asking for, but it is not enabled by default on purpose.

like image 95
Eric Anderson Avatar answered Oct 04 '22 20:10

Eric Anderson