Back to results for “Error Handling”
.NET › gRPC Services

How does gRPC handle errors and status codes, and how does this differ from HTTP status codes in REST?

Advanced

Answer

gRPC uses its own set of standardized status codes (like NotFound, InvalidArgument, PermissionDenied, Internal, Unavailable) distinct from HTTP status codes, communicated via gRPC trailers rather than the HTTP status line -- a server method throws an RpcException with a specific StatusCode and optional detail message, which the client-side generated code surfaces as a corresponding exception, giving a richer, RPC-appropriate error vocabulary than REST's more general-purpose HTTP status codes.
public override Task<OrderResponse> GetOrder(GetOrderRequest request, ServerCallContext context) {
    var order = _repository.Find(request.OrderId);
    if (order == null) {
        throw new RpcException(new Status(StatusCode.NotFound, $"Order {request.OrderId} not found"));
    }
    return Task.FromResult(MapToResponse(order));
}

// Client-side:
try {
    var response = await client.GetOrderAsync(request);
} catch (RpcException ex) when (ex.StatusCode == StatusCode.NotFound) {
    // handle specifically
}
Real-world example A gRPC client library automatically translates a server-thrown RpcException with StatusCode.PermissionDenied into a client-side exception the calling application can catch and handle specifically, distinct from how it would handle a StatusCode.Unavailable indicating a transient network issue.

Common follow-ups: How do you attach custom error details (like field-level validation errors) to an RpcException?;How does gRPC status code mapping relate to HTTP status codes when gRPC runs over HTTP/2?