How do you handle and propagate errors in gRPC, given it doesn't use standard HTTP status codes the way REST does?
Short answer
gRPC uses its own status code system (RpcException with a StatusCode like NotFound, InvalidArgument, PermissionDenied) distinct from HTTP status codes, thrown by the server and automatically translated into the equivalent gRPC status on the wire, which the client catches as an…
Advertisement
AModel answer
gRPC uses its own status code system (RpcException with a StatusCode like NotFound, InvalidArgument, PermissionDenied) distinct from HTTP status codes, thrown by the server and automatically translated into the equivalent gRPC status on the wire, which the client catches as an RpcException with a matching StatusCode property -- richer error details can be attached via google.rpc.Status metadata for structured error information beyond just a status code and message.
public override Task<Item> GetItem(ItemRequest request, ServerCallContext context) {
var item = _repository.Find(request.Id);
if (item is null)
throw new RpcException(new Status(StatusCode.NotFound, $"Item {request.Id} not found"));
return Task.FromResult(item);
}
// Client-side handling
try {
var item = await client.GetItemAsync(request);
} catch (RpcException ex) when (ex.StatusCode == StatusCode.NotFound) {
// handle not-found case
}Real-world example
A gRPC inventory service throws an RpcException with StatusCode.NotFound when queried for a nonexistent product, which the calling order service catches specifically by that status code to trigger its own appropriate fallback behavior.
Likely follow-ups
- How do gRPC status codes map (or fail to map cleanly) to HTTP status codes when using gRPC-Web through a proxy?
- How would you implement a gRPC interceptor for centralized error logging?
Related topics