Catch.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Runtime.ExceptionServices;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerableEx
  11. {
  12. // REVIEW: All Catch operators may catch OperationCanceledException due to cancellation of the enumeration
  13. // of the source. Should we explicitly avoid handling this? E.g. as follows:
  14. //
  15. // catch (TException ex) when(!(ex is OperationCanceledException oce && oce.CancellationToken == cancellationToken))
  16. /// <summary>
  17. /// Continues an async-enumerable sequence that is terminated by an exception of the specified type with the async-enumerable sequence produced by the handler.
  18. /// </summary>
  19. /// <typeparam name="TSource">The type of the elements in the source sequence and sequences returned by the exception handler function.</typeparam>
  20. /// <typeparam name="TException">The type of the exception to catch and handle. Needs to derive from <see cref="Exception"/>.</typeparam>
  21. /// <param name="source">Source sequence.</param>
  22. /// <param name="handler">Exception handler function, producing another async-enumerable sequence.</param>
  23. /// <returns>An async-enumerable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting async-enumerable sequence in case an exception occurred.</returns>
  24. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="handler"/> is null.</exception>
  25. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, IAsyncEnumerable<TSource>> handler)
  26. where TException : Exception
  27. {
  28. if (source == null)
  29. throw Error.ArgumentNull(nameof(source));
  30. if (handler == null)
  31. throw Error.ArgumentNull(nameof(handler));
  32. #if HAS_ASYNC_ENUMERABLE_CANCELLATION
  33. return Core(source, handler);
  34. static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TException, IAsyncEnumerable<TSource>> handler, [System.Runtime.CompilerServices.EnumeratorCancellation]CancellationToken cancellationToken = default)
  35. #else
  36. return AsyncEnumerable.Create(Core);
  37. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  38. #endif
  39. {
  40. // REVIEW: This implementation mirrors the Ix implementation, which does not protect GetEnumerator
  41. // using the try statement either. A more trivial implementation would use await foreach
  42. // and protect the entire loop using a try statement, with two breaking changes:
  43. //
  44. // - Also protecting the call to GetAsyncEnumerator by the try statement.
  45. // - Invocation of the handler after disposal of the failed first sequence.
  46. var err = default(IAsyncEnumerable<TSource>);
  47. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  48. {
  49. while (true)
  50. {
  51. TSource c;
  52. try
  53. {
  54. if (!await e.MoveNextAsync())
  55. break;
  56. c = e.Current;
  57. }
  58. catch (TException ex)
  59. {
  60. err = handler(ex);
  61. break;
  62. }
  63. yield return c;
  64. }
  65. }
  66. if (err != null)
  67. {
  68. await foreach (var item in err.WithCancellation(cancellationToken).ConfigureAwait(false))
  69. {
  70. yield return item;
  71. }
  72. }
  73. }
  74. }
  75. /// <summary>
  76. /// Continues an async-enumerable sequence that is terminated by an exception of the specified type with the async-enumerable sequence produced asynchronously by the handler.
  77. /// </summary>
  78. /// <typeparam name="TSource">The type of the elements in the source sequence and sequences returned by the exception handler function.</typeparam>
  79. /// <typeparam name="TException">The type of the exception to catch and handle. Needs to derive from <see cref="Exception"/>.</typeparam>
  80. /// <param name="source">Source sequence.</param>
  81. /// <param name="handler">Exception handler function, producing another async-enumerable sequence asynchronously.</param>
  82. /// <returns>An async-enumerable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting async-enumerable sequence in case an exception occurred.</returns>
  83. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="handler"/> is null.</exception>
  84. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler)
  85. where TException : Exception
  86. {
  87. if (source == null)
  88. throw Error.ArgumentNull(nameof(source));
  89. if (handler == null)
  90. throw Error.ArgumentNull(nameof(handler));
  91. #if HAS_ASYNC_ENUMERABLE_CANCELLATION
  92. return Core(source, handler);
  93. static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler, [System.Runtime.CompilerServices.EnumeratorCancellation]CancellationToken cancellationToken = default)
  94. #else
  95. return AsyncEnumerable.Create(Core);
  96. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  97. #endif
  98. {
  99. // REVIEW: This implementation mirrors the Ix implementation, which does not protect GetEnumerator
  100. // using the try statement either. A more trivial implementation would use await foreach
  101. // and protect the entire loop using a try statement, with two breaking changes:
  102. //
  103. // - Also protecting the call to GetAsyncEnumerator by the try statement.
  104. // - Invocation of the handler after disposal of the failed first sequence.
  105. var err = default(IAsyncEnumerable<TSource>);
  106. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  107. {
  108. while (true)
  109. {
  110. TSource c;
  111. try
  112. {
  113. if (!await e.MoveNextAsync())
  114. break;
  115. c = e.Current;
  116. }
  117. catch (TException ex)
  118. {
  119. err = await handler(ex).ConfigureAwait(false);
  120. break;
  121. }
  122. yield return c;
  123. }
  124. }
  125. if (err != null)
  126. {
  127. await foreach (var item in err.WithCancellation(cancellationToken).ConfigureAwait(false))
  128. {
  129. yield return item;
  130. }
  131. }
  132. }
  133. }
  134. #if !NO_DEEP_CANCELLATION
  135. /// <summary>
  136. /// Continues an async-enumerable sequence that is terminated by an exception of the specified type with the async-enumerable sequence produced asynchronously (cancellable) by the handler.
  137. /// </summary>
  138. /// <typeparam name="TSource">The type of the elements in the source sequence and sequences returned by the exception handler function.</typeparam>
  139. /// <typeparam name="TException">The type of the exception to catch and handle. Needs to derive from <see cref="Exception"/>.</typeparam>
  140. /// <param name="source">Source sequence.</param>
  141. /// <param name="handler">Exception handler function, producing another async-enumerable sequence asynchronously while supporting cancellation.</param>
  142. /// <returns>An async-enumerable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting async-enumerable sequence in case an exception occurred.</returns>
  143. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="handler"/> is null.</exception>
  144. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler)
  145. where TException : Exception
  146. {
  147. if (source == null)
  148. throw Error.ArgumentNull(nameof(source));
  149. if (handler == null)
  150. throw Error.ArgumentNull(nameof(handler));
  151. #if HAS_ASYNC_ENUMERABLE_CANCELLATION
  152. return Core(source, handler);
  153. static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler, [System.Runtime.CompilerServices.EnumeratorCancellation]CancellationToken cancellationToken = default)
  154. #else
  155. return AsyncEnumerable.Create(Core);
  156. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  157. #endif
  158. {
  159. // REVIEW: This implementation mirrors the Ix implementation, which does not protect GetEnumerator
  160. // using the try statement either. A more trivial implementation would use await foreach
  161. // and protect the entire loop using a try statement, with two breaking changes:
  162. //
  163. // - Also protecting the call to GetAsyncEnumerator by the try statement.
  164. // - Invocation of the handler after disposal of the failed first sequence.
  165. var err = default(IAsyncEnumerable<TSource>);
  166. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  167. {
  168. while (true)
  169. {
  170. TSource c;
  171. try
  172. {
  173. if (!await e.MoveNextAsync())
  174. break;
  175. c = e.Current;
  176. }
  177. catch (TException ex)
  178. {
  179. err = await handler(ex, cancellationToken).ConfigureAwait(false);
  180. break;
  181. }
  182. yield return c;
  183. }
  184. }
  185. if (err != null)
  186. {
  187. await foreach (var item in err.WithCancellation(cancellationToken).ConfigureAwait(false))
  188. {
  189. yield return item;
  190. }
  191. }
  192. }
  193. }
  194. #endif
  195. /// <summary>
  196. /// Continues an async-enumerable sequence that is terminated by an exception with the next async-enumerable sequence.
  197. /// </summary>
  198. /// <typeparam name="TSource">The type of the elements in the source and handler sequences.</typeparam>
  199. /// <param name="sources">Observable sequences to catch exceptions for.</param>
  200. /// <returns>An async-enumerable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.</returns>
  201. /// <exception cref="ArgumentNullException"><paramref name="sources"/> is null.</exception>
  202. public static IAsyncEnumerable<TSource> Catch<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  203. {
  204. if (sources == null)
  205. throw Error.ArgumentNull(nameof(sources));
  206. return CatchCore(sources);
  207. }
  208. /// <summary>
  209. /// Continues an async-enumerable sequence that is terminated by an exception with the next async-enumerable sequence.
  210. /// </summary>
  211. /// <typeparam name="TSource">The type of the elements in the source and handler sequences.</typeparam>
  212. /// <param name="sources">Observable sequences to catch exceptions for.</param>
  213. /// <returns>An async-enumerable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.</returns>
  214. /// <exception cref="ArgumentNullException"><paramref name="sources"/> is null.</exception>
  215. public static IAsyncEnumerable<TSource> Catch<TSource>(params IAsyncEnumerable<TSource>[] sources)
  216. {
  217. if (sources == null)
  218. throw Error.ArgumentNull(nameof(sources));
  219. return CatchCore(sources);
  220. }
  221. /// <summary>
  222. /// Continues an async-enumerable sequence that is terminated by an exception with the next async-enumerable sequence.
  223. /// </summary>
  224. /// <typeparam name="TSource">The type of the elements in the source sequence and handler sequence.</typeparam>
  225. /// <param name="first">First async-enumerable sequence whose exception (if any) is caught.</param>
  226. /// <param name="second">Second async-enumerable sequence used to produce results when an error occurred in the first sequence.</param>
  227. /// <returns>An async-enumerable sequence containing the first sequence's elements, followed by the elements of the second sequence in case an exception occurred.</returns>
  228. /// <exception cref="ArgumentNullException"><paramref name="first"/> or <paramref name="second"/> is null.</exception>
  229. public static IAsyncEnumerable<TSource> Catch<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  230. {
  231. if (first == null)
  232. throw Error.ArgumentNull(nameof(first));
  233. if (second == null)
  234. throw Error.ArgumentNull(nameof(second));
  235. return CatchCore(new[] { first, second });
  236. }
  237. private static IAsyncEnumerable<TSource> CatchCore<TSource>(IEnumerable<IAsyncEnumerable<TSource>> sources)
  238. {
  239. return AsyncEnumerable.Create(Core);
  240. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  241. {
  242. var error = default(ExceptionDispatchInfo);
  243. foreach (var source in sources)
  244. {
  245. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  246. error = null;
  247. while (true)
  248. {
  249. TSource c;
  250. try
  251. {
  252. if (!await e.MoveNextAsync())
  253. break;
  254. c = e.Current;
  255. }
  256. catch (Exception ex)
  257. {
  258. error = ExceptionDispatchInfo.Capture(ex);
  259. break;
  260. }
  261. yield return c;
  262. }
  263. if (error == null)
  264. break;
  265. }
  266. error?.Throw();
  267. }
  268. }
  269. }
  270. }