Question
What is the pattern for sending more details about errors to the client using gRPC?
For example, suppose I have a form for registering a user, that sends a message
message RegisterUser {
string email = 1;
string password = 2;
}
where the email has to be properly formatted and unique, and the password must be at least 8 characters long.
If I was writing a JSON API, I'd return a 400 error with the following body:
{
"errors": [{
"field": "email",
"message": "Email does not have proper format."
}, {
"field": "password",
"message": "Password must be at least 8 characters."
}],
}
and the client could provide nice error messages to the user (i.e. by highlighting the password field and specifically telling the user that there's something wrong with their input to it).
With gRPC is there a way to do something similar? It seems that in most client languages, an error results in an exception being thrown, with no way to grab the response.
For example, I'd like something like
message ValidationError {
string field = 1;
string message = 2;
}
message RegisterUserResponse {
repeated ValidationError validation_errors = 1;
...
}
or similar.
Answer
Include additional error details in the response Metadata. However, still make
sure to provide a useful status code and message. In this case, you can add
RegisterUserResponse
to the Metadata.
In gRPC Java, that would look like:
Metadata.Key<RegisterUserResponse> REGISTER_USER_RESPONSE_KEY =
ProtoUtils.keyForProto(RegisterUserResponse.getDefaultInstance());
...
Metadata metadata = new Metadata();
metadata.put(REGISTER_USER_RESPONSE_KEY, registerUserResponse);
responseObserver.onError(
Status.INVALID_ARGUMENT.withDescription("Email or password malformed")
.asRuntimeException(metadata));
Another option is to use the google.rpc.Status
proto
which includes an additional Any
for details
. Support is coming to each
language to handle the type. In Java, it'd look like:
// This is com.google.rpc.Status, not io.grpc.Status
Status status = Status.newBuilder()
.setCode(Code.INVALID_ARGUMENT.getNumber())
.setMessage("Email or password malformed")
.addDetails(Any.pack(registerUserResponse))
.build();
responseObserver.onError(StatusProto.toStatusRuntimeException(status));
google.rpc.Status
is cleaner in some languages as the error details can be
passed around as one unit. It also makes it clear what parts of the response
are error-related. On-the-wire, it still uses Metadata to pass the additional
information.
You may also be interested in error_details.proto which contains some common types of errors.
I [discussed this topic](https://kccncna17.sched.com/event/CU7e/modifying- grpc-services-over-time-i-eric-anderson-google) during CloudNativeCon. You can check out the slides and linked recording on YouTube.