csharp / expert
Snippet
Higher-Order Functional Retries
Uses higher-order functions and exception filters to implement a reusable retry mechanism. The 'when' clause ensures the catch block only triggers if more attempts remain, maintaining the stack trace if the last one fails.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
public static T ExecuteWithRetry<T>(Func<T> action, int attempts = 3){for (int i = 0; i < attempts; i++){try { return action(); }catch (Exception) when (i < attempts - 1) { /* Log retry */ }}throw new InvalidOperationException("Final attempt failed.");}
Breakdown
1
Func<T> action
Accepts a delegate representing the logic to be executed.
2
catch (Exception) when (i < attempts - 1)
Exception filter that prevents catching the exception on the final loop iteration.