8

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.

2 Answers 2

0

You can return custom KV pairs in trailing metadata.

Example from unit test: https://github.com/grpc/grpc/blob/master/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py#L430

Sign up to request clarification or add additional context in comments.

Comments

0

There is an example for returning custom error at https://github.com/grpc/grpc/tree/master/examples/python/errors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.