csharp / expert
Snippet
Resilience Pipelines via Higher-Order Delegates
Advanced error handling utilizes higher-order functions and exception filters (`when`) to decouple business logic from resilience strategies. By passing delegates and using generic constraints, you can create reusable execution wrappers that handle specific failure states without polluting the primary code path.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static class FaultTolerance{public static T ExecuteWithFallback<T, TException>(Func<T> action,Func<TException, T> fallback) where TException : Exception{try{return action();}catch (TException ex) when (ex.Data.Contains("Retryable")){return fallback(ex);}}public static async Task<T> WrapAsync<T>(Func<Task<T>> operation){// Higher-order function that adds logging context to any taskvar result = await operation();return result;}}
Breakdown
1
catch (TException ex) when (ex.Data.Contains("Retryable"))
An exception filter that allows the catch block to trigger only if a specific runtime condition is met.
2
Func<TException, T> fallback
A delegate passed as an argument to handle the recovery logic if the primary operation fails.