首页 > 解决方案 > 从流中读取时,Grpc 服务器中未处理异常

问题描述

我制作了一个简单的应用程序,其中文件块从客户端流式传输到服务器。服务器端我已经处理了异常,以便将我自己的响应返回给客户端。但是,当我在从流中读取完成之前抛出异常时,即使它被捕获并返回了自定义响应,客户端我仍然会得到一个未处理RpcException的状态Cancelled

public override async Task<UploadFileResponse> UploadFile(
        IAsyncStreamReader<UploadFileRequest> requestStream,
        ServerCallContext context)
    {
        try
        {
            bool moveNext = await requestStream.MoveNext();
            using (var stream = System.IO.File.Create($"foo.txt"))
            {
                while (moveNext)
                {
                    // If something goes wrong here, before the stream has been fully read, an RpcException
                    // of status Cancelled is caught in the client instead of receiving an UploadFileResponse of
                    // type 'Failed'. Despite the fact that we catch it in the server and return a Failed response.
                    await stream.WriteAsync(requestStream.Current.Data.ToByteArray());
                    moveNext = await requestStream.MoveNext();
                    throw new Exception();
                }
                // If something goes wrong here, when the stream has been fully read, we catch it and successfully return
                // a response of our own instead of an RpcException.
                // throw new Exception();
            }

            return new UploadFileResponse()
            {
                StatusCode = UploadStatusCode.Ok
            };
        }
        catch (Exception ex)
        {
            return new UploadFileResponse()
            {
                Message = ex.Message,
                StatusCode = UploadStatusCode.Failed
            };
        }

    }

也许我实现此操作的方式是错误的。我可以看到为什么服务器会返回CancelledRPC 异常,因为我们确实在流被完全读取之前取消了调用,但我不明白为什么它会覆盖自定义响应。可能必须在客户端处理这两者 - 响应失败和潜在的 RPC 异常。

标签: c#asp.net-coregrpc

解决方案


我找到了一些关于该主题的材料 -服务器客户端

显然,当出现无效响应时抛出 RpcExceptions 是很常见的,如官方 gRPC Github 存储库所示


推荐阅读