简体   繁体   中英

Exception not handled in Grpc server when reading from a stream

I made a simple app where chunks of a file are streamed from client to server. Server-side I have handled exceptions such that a response of my own is returned to the client. When I throw an exception before reading from the stream has been completed, however, even though it gets caught and a custom response is returned, client-side I still get an unhandled RpcException with status 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
            };
        }

    }

Perhaps the way I approach implementing this operation is wrong. I can see why the server would return a Cancelled RPC exception because we indeed cancel the call before the stream has been fully read but I don't understand why it overrides the custom response. It might be that handling both would have to be done client-side - a failed response and a potential RPC exception.

I found some materials on the topic - Server and Client .

Apparently it is common to throw RpcExceptions whenever there should be an invalid response as also shown in the official gRPC Github repository here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM