I have a .proto file:
// Protocol Buffers Language version
syntax = "proto3";
package my_package;
// -----------------Cart service-----------------
service CartService {
rpc AddItem(AddItemRequest) returns (AddItemResponse) {}
}
message CartItem {
string product_id = 1;
int32 quantity = 2;
}
message AddItemRequest {
string user_id = 1;
CartItem item = 2;
}
message AddItemResponse {
string user_id = 1;
}
In my AddItem method I want to return a custom error like cart_not_found:
class CartService(my_package_pb2_grpc.CartServiceServicer):
def AddItem(self, request, context):
context.set_code(StatusCode.CART_NOT_FOUND)
context.set_details('Cart Not Found!')
return context
The above code does not work as gRPC status codes are limited to some basic list. How can I return custom errors in gRPC?
EDIT-1:
I've seen examples that set machine readable code in details like below:
context.set_code(grpc.StatusCode.INTERNAL)
context.set_details('cart_not_found')
return context
But this has its own limitation and I cannot set description for the error or any other custom key.
The other method is to return error in every message you have like below:
message AddItemResponse {
string user_id = 1;
Error error = 2;
}
message Error {
string code = 1;
string message = 2;
}
This implementation has one drawback that services need to check for error existence and then handle the error otherwise process the response.