Sobes.tech
Junior — Middle

How does gRPC handle and transmit response statuses?

sobes.tech AI

Answer from AI

gRPC uses its own mechanism for transmitting response statuses, based on the Status object. Each gRPC response contains a status code (e.g., OK, NOT_FOUND, INTERNAL, etc.) and an optional message describing the error.

When a call completes, the server sets the status, which the client receives along with the response. In Go, this is usually handled through the returned error value, which can be converted into a gRPC status using the status package.

Example of handling status in Go:

import (
    "context"
    "google.golang.org/grpc/status"
    "google.golang.org/grpc/codes"
)

func (s *server) SomeRPC(ctx context.Context, req *Request) (*Response, error) {
    if someErrorCondition {
        return nil, status.Error(codes.NotFound, "resource not found")
    }
    return &Response{Data: "ok"}, nil
}

The client can check the error status like this:

resp, err := client.SomeRPC(ctx, req)
if err != nil {
    st, ok := status.FromError(err)
    if ok && st.Code() == codes.NotFound {
        // handle NOT_FOUND error
    }
}

Thus, gRPC transmits statuses via code and message, allowing the client to accurately understand the result of the call.

How does gRPC handle and transmit response statuses… - sobes.tech