|
1 | 1 | using System; |
2 | 2 | using Grpc.Core; |
3 | 3 | using Grpc.Core.Interceptors; |
| 4 | +using System.Threading.Tasks; |
4 | 5 |
|
5 | 6 | namespace Bones.Grpc |
6 | 7 | { |
7 | 8 | public class NotFoundInterceptor : Interceptor |
8 | 9 | { |
9 | | - public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncUnaryCallContinuation<TRequest, TResponse> continuation) |
| 10 | + public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>( |
| 11 | + TRequest request, |
| 12 | + ClientInterceptorContext<TRequest, TResponse> context, |
| 13 | + AsyncUnaryCallContinuation<TRequest, TResponse> continuation) |
10 | 14 | { |
11 | | - var response = base.AsyncUnaryCall(request, context, continuation); |
| 15 | + var call = continuation(request, context); |
12 | 16 |
|
13 | | - var responseWithErrorhandling = response.ResponseAsync.ContinueWith( |
14 | | - r => { |
15 | | - try |
16 | | - { |
17 | | - var response = r.Result; |
18 | | - return response; |
19 | | - } |
20 | | - catch (AggregateException ex) |
21 | | - { |
22 | | - if(ex.InnerException is RpcException rpcException |
23 | | - && rpcException.StatusCode == StatusCode.NotFound){ |
24 | | - return null; |
25 | | - } |
26 | | - throw; |
27 | | - } |
28 | | - } |
29 | | - ); |
| 17 | + return new AsyncUnaryCall<TResponse>( |
| 18 | + HandleResponse(call.ResponseAsync), |
| 19 | + call.ResponseHeadersAsync, |
| 20 | + call.GetStatus, |
| 21 | + call.GetTrailers, |
| 22 | + call.Dispose); |
| 23 | + } |
30 | 24 |
|
31 | | - return new AsyncUnaryCall<TResponse>(responseWithErrorhandling, response.ResponseHeadersAsync, response.GetStatus, response.GetTrailers, response.Dispose); |
| 25 | + private async Task<TResponse> HandleResponse<TResponse>(Task<TResponse> task) |
| 26 | + { |
| 27 | + try |
| 28 | + { |
| 29 | + return await task; |
| 30 | + } |
| 31 | + catch (RpcException ex) when (ex.StatusCode == StatusCode.NotFound) |
| 32 | + { |
| 33 | + return default; |
| 34 | + } |
32 | 35 | } |
33 | 36 | } |
34 | 37 | } |
0 commit comments