Catch.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. return Core(source, handler);
  33. static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TException, IAsyncEnumerable<TSource>> handler, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  34. {
  35. // REVIEW: This implementation mirrors the Ix implementation, which does not protect GetEnumerator
  36. // using the try statement either. A more trivial implementation would use await foreach
  37. // and protect the entire loop using a try statement, with two breaking changes:
  38. //
  39. // - Also protecting the call to GetAsyncEnumerator by the try statement.
  40. // - Invocation of the handler after disposal of the failed first sequence.
  41. var err = default(IAsyncEnumerable<TSource>);
  42. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  43. {
  44. while (true)
  45. {
  46. TSource c;
  47. try
  48. {
  49. if (!await e.MoveNextAsync())
  50. break;
  51. c = e.Current;
  52. }
  53. catch (TException ex)
  54. {
  55. err = handler(ex);
  56. break;
  57. }
  58. yield return c;
  59. }
  60. }
  61. if (err != null)
  62. {
  63. await foreach (var item in err.WithCancellation(cancellationToken).ConfigureAwait(false))
  64. {
  65. yield return item;
  66. }
  67. }
  68. }
  69. }
  70. /// <summary>
  71. /// 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.
  72. /// </summary>
  73. /// <typeparam name="TSource">The type of the elements in the source sequence and sequences returned by the exception handler function.</typeparam>
  74. /// <typeparam name="TException">The type of the exception to catch and handle. Needs to derive from <see cref="Exception"/>.</typeparam>
  75. /// <param name="source">Source sequence.</param>
  76. /// <param name="handler">Exception handler function, producing another async-enumerable sequence asynchronously.</param>
  77. /// <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>
  78. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="handler"/> is null.</exception>
  79. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler)
  80. where TException : Exception
  81. {
  82. if (source == null)
  83. throw Error.ArgumentNull(nameof(source));
  84. if (handler == null)
  85. throw Error.ArgumentNull(nameof(handler));
  86. return Core(source, handler);
  87. static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  88. {
  89. // REVIEW: This implementation mirrors the Ix implementation, which does not protect GetEnumerator
  90. // using the try statement either. A more trivial implementation would use await foreach
  91. // and protect the entire loop using a try statement, with two breaking changes:
  92. //
  93. // - Also protecting the call to GetAsyncEnumerator by the try statement.
  94. // - Invocation of the handler after disposal of the failed first sequence.
  95. var err = default(IAsyncEnumerable<TSource>);
  96. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  97. {
  98. while (true)
  99. {
  100. TSource c;
  101. try
  102. {
  103. if (!await e.MoveNextAsync())
  104. break;
  105. c = e.Current;
  106. }
  107. catch (TException ex)
  108. {
  109. err = await handler(ex).ConfigureAwait(false);
  110. break;
  111. }
  112. yield return c;
  113. }
  114. }
  115. if (err != null)
  116. {
  117. await foreach (var item in err.WithCancellation(cancellationToken).ConfigureAwait(false))
  118. {
  119. yield return item;
  120. }
  121. }
  122. }
  123. }
  124. #if !NO_DEEP_CANCELLATION
  125. /// <summary>
  126. /// 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.
  127. /// </summary>
  128. /// <typeparam name="TSource">The type of the elements in the source sequence and sequences returned by the exception handler function.</typeparam>
  129. /// <typeparam name="TException">The type of the exception to catch and handle. Needs to derive from <see cref="Exception"/>.</typeparam>
  130. /// <param name="source">Source sequence.</param>
  131. /// <param name="handler">Exception handler function, producing another async-enumerable sequence asynchronously while supporting cancellation.</param>
  132. /// <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>
  133. /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="handler"/> is null.</exception>
  134. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler)
  135. where TException : Exception
  136. {
  137. if (source == null)
  138. throw Error.ArgumentNull(nameof(source));
  139. if (handler == null)
  140. throw Error.ArgumentNull(nameof(handler));
  141. return Core(source, handler);
  142. static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  143. {
  144. // REVIEW: This implementation mirrors the Ix implementation, which does not protect GetEnumerator
  145. // using the try statement either. A more trivial implementation would use await foreach
  146. // and protect the entire loop using a try statement, with two breaking changes:
  147. //
  148. // - Also protecting the call to GetAsyncEnumerator by the try statement.
  149. // - Invocation of the handler after disposal of the failed first sequence.
  150. var err = default(IAsyncEnumerable<TSource>);
  151. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  152. {
  153. while (true)
  154. {
  155. TSource c;
  156. try
  157. {
  158. if (!await e.MoveNextAsync())
  159. break;
  160. c = e.Current;
  161. }
  162. catch (TException ex)
  163. {
  164. err = await handler(ex, cancellationToken).ConfigureAwait(false);
  165. break;
  166. }
  167. yield return c;
  168. }
  169. }
  170. if (err != null)
  171. {
  172. await foreach (var item in err.WithCancellation(cancellationToken).ConfigureAwait(false))
  173. {
  174. yield return item;
  175. }
  176. }
  177. }
  178. }
  179. #endif
  180. /// <summary>
  181. /// Continues an async-enumerable sequence that is terminated by an exception with the next async-enumerable sequence.
  182. /// </summary>
  183. /// <typeparam name="TSource">The type of the elements in the source and handler sequences.</typeparam>
  184. /// <param name="sources">Observable sequences to catch exceptions for.</param>
  185. /// <returns>An async-enumerable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.</returns>
  186. /// <exception cref="ArgumentNullException"><paramref name="sources"/> is null.</exception>
  187. public static IAsyncEnumerable<TSource> Catch<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  188. {
  189. if (sources == null)
  190. throw Error.ArgumentNull(nameof(sources));
  191. return CatchCore(sources);
  192. }
  193. /// <summary>
  194. /// Continues an async-enumerable sequence that is terminated by an exception with the next async-enumerable sequence.
  195. /// </summary>
  196. /// <typeparam name="TSource">The type of the elements in the source and handler sequences.</typeparam>
  197. /// <param name="sources">Observable sequences to catch exceptions for.</param>
  198. /// <returns>An async-enumerable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.</returns>
  199. /// <exception cref="ArgumentNullException"><paramref name="sources"/> is null.</exception>
  200. public static IAsyncEnumerable<TSource> Catch<TSource>(params IAsyncEnumerable<TSource>[] sources)
  201. {
  202. if (sources == null)
  203. throw Error.ArgumentNull(nameof(sources));
  204. return CatchCore(sources);
  205. }
  206. /// <summary>
  207. /// Continues an async-enumerable sequence that is terminated by an exception with the next async-enumerable sequence.
  208. /// </summary>
  209. /// <typeparam name="TSource">The type of the elements in the source sequence and handler sequence.</typeparam>
  210. /// <param name="first">First async-enumerable sequence whose exception (if any) is caught.</param>
  211. /// <param name="second">Second async-enumerable sequence used to produce results when an error occurred in the first sequence.</param>
  212. /// <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>
  213. /// <exception cref="ArgumentNullException"><paramref name="first"/> or <paramref name="second"/> is null.</exception>
  214. public static IAsyncEnumerable<TSource> Catch<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  215. {
  216. if (first == null)
  217. throw Error.ArgumentNull(nameof(first));
  218. if (second == null)
  219. throw Error.ArgumentNull(nameof(second));
  220. return CatchCore(new[] { first, second });
  221. }
  222. private static async IAsyncEnumerable<TSource> CatchCore<TSource>(IEnumerable<IAsyncEnumerable<TSource>> sources, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
  223. {
  224. var error = default(ExceptionDispatchInfo);
  225. foreach (var source in sources)
  226. {
  227. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  228. error = null;
  229. while (true)
  230. {
  231. TSource c;
  232. try
  233. {
  234. if (!await e.MoveNextAsync())
  235. break;
  236. c = e.Current;
  237. }
  238. catch (Exception ex)
  239. {
  240. error = ExceptionDispatchInfo.Capture(ex);
  241. break;
  242. }
  243. yield return c;
  244. }
  245. if (error == null)
  246. break;
  247. }
  248. error?.Throw();
  249. }
  250. }
  251. }