|
2 | 2 | using System;
|
3 | 3 | using System.Collections.Generic;
|
4 | 4 | using System.ComponentModel;
|
| 5 | +using System.IO; |
5 | 6 | using System.Runtime.CompilerServices;
|
| 7 | +using System.Security; |
6 | 8 | using System.Threading;
|
7 | 9 | using System.Threading.Tasks;
|
8 | 10 | namespace ProtoBuf.Grpc.Internal
|
@@ -136,6 +138,68 @@ public static async Task WriteTo<T>(this IAsyncEnumerable<T> reader, IServerStre
|
136 | 138 | }
|
137 | 139 | }
|
138 | 140 |
|
| 141 | + /// <summary> |
| 142 | + /// Consumes the provided task raising exceptions as <see cref="RpcException"/> |
| 143 | + /// </summary> |
| 144 | + [Obsolete(WarningMessage, false)] |
| 145 | + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] |
| 146 | + public static Task WithSimpleExceptionHandling(Task task) |
| 147 | + { |
| 148 | + return task.RanToCompletion() ? Task.CompletedTask : Awaited(task); |
| 149 | + |
| 150 | + static async Task Awaited(Task task) |
| 151 | + { |
| 152 | + try |
| 153 | + { |
| 154 | + await task.ConfigureAwait(false); |
| 155 | + } |
| 156 | + catch (Exception ex) when (!(ex is RpcException)) |
| 157 | + { |
| 158 | + Rethrow(ex); |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + /// <summary> |
| 164 | + /// Consumes the provided task raising exceptions as <see cref="RpcException"/> |
| 165 | + /// </summary> |
| 166 | + [Obsolete(WarningMessage, false)] |
| 167 | + [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] |
| 168 | + public static Task<T> WithSimpleExceptionHandling<T>(Task<T> task) |
| 169 | + { |
| 170 | + return task.RanToCompletion() ? task : Awaited(task); |
| 171 | + |
| 172 | + static async Task<T> Awaited(Task<T> task) |
| 173 | + { |
| 174 | + try |
| 175 | + { |
| 176 | + return await task.ConfigureAwait(false); |
| 177 | + } |
| 178 | + catch (Exception ex) when (!(ex is RpcException)) |
| 179 | + { |
| 180 | + Rethrow(ex); |
| 181 | + return default!; // never reached |
| 182 | + } |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + private static void Rethrow(Exception ex) |
| 187 | + { |
| 188 | + var code = ex switch |
| 189 | + { |
| 190 | + OperationCanceledException => StatusCode.Cancelled, |
| 191 | + ArgumentException => StatusCode.InvalidArgument, |
| 192 | + NotImplementedException => StatusCode.Unimplemented, |
| 193 | + SecurityException => StatusCode.PermissionDenied, |
| 194 | + EndOfStreamException => StatusCode.OutOfRange, |
| 195 | + FileNotFoundException => StatusCode.NotFound, |
| 196 | + DirectoryNotFoundException => StatusCode.NotFound, |
| 197 | + TimeoutException => StatusCode.DeadlineExceeded, |
| 198 | + _ => StatusCode.Unknown, |
| 199 | + }; |
| 200 | + throw new RpcException(new Status(code, ex.Message), ex.Message); |
| 201 | + } |
| 202 | + |
139 | 203 | /// <summary>
|
140 | 204 | /// Performs a gRPC blocking unary call
|
141 | 205 | /// </summary>
|
|
0 commit comments