c# - 从流中读取时,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
};
}
}
也许我实现此操作的方式是错误的。我可以看到为什么服务器会返回Cancelled
RPC 异常,因为我们确实在流被完全读取之前取消了调用,但我不明白为什么它会覆盖自定义响应。可能必须在客户端处理这两者 - 响应失败和潜在的 RPC 异常。
解决方案
推荐阅读
- javascript - 结合 settimeout 和 label Loop 和 if 语句
- javascript - 如果选中复选框,我如何在复选框旁边的文本中运行一行?
- python - 从python中的excel文件名中提取日期
- python - 熊猫数据框根据条件替换值
- flutter - 如何在颤动中获取歌曲的封面图片(专辑封面)?
- python - ValueError:无法将字符串转换为浮点数:'W'
- json - 将字符串文字添加到 JSONPath 输出中
- flutter - 查看 mainAxisSize 效果的最低设置是多少?
- react-native - 如何在 react-native 的不同屏幕上以编程方式设置 windowSoftInputMode?
- html - 想用引导导航栏制作背景png,但它不起作用