grpc-dotnet: Returning null from a grpc interceptor when there is a failure status code

Why can’t return null from an interceptor there is a failure status code.

public class TestInterceptor : Interceptor
{
    public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod<TRequest, TResponse> continuation)
    {
        if (Some Logic)
        {
            return await  continuation(request, context);
        }
        context.Status = new Status(StatusCode.Unavailable, "Some information about the issue");
        return null!;
    }
}

I don’t think I’m supposed to return a response when there is a failure status code. Or do I? When I return null with failure status code I get this error message

Grpc.Core.RpcException: Status(StatusCode="Cancelled", Detail="No message returned from method.")
at Grpc.AspNetCore.Server.Internal.CallHandlers.UnaryServerCallHandler`3.HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext)

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 1
  • Comments: 16 (9 by maintainers)

Most upvoted comments

We use MessagePack for Marshaller instead of protobuf, so it is possible to serialize null. This means that a Unary method implementation that returns null as TResponse in Method<TRequest, TResponse> can still send a message body.

However, as discussed here, Grpc.AspNetCore.Server will block if it receives null.😢

Yeah, the performance difference for the exceptions is most of the time is unnoticeable and negligible. But what about other times?

gRPC doesn’t use exceptions in typical application flow. If an HTTP request is being canceled, causing gRPC to throw a RpcException, an exception being thrown will have no impact at all on performance.