You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Throwing an exception in an user-defined delegate is never a good idea
It is breaking the normal control flow
✅ DO
Use ExecuteAndCapture and then FinalException
varresult= whateverPolicy.ExecuteAndCapture(...);if(result.Outcome != OutcomeType.Successful && result.FinalExecption is HttpRequestException)thrownew CustomNetworkException(result.FinalExecption)
Reasoning:
This approach executes the policy/policies without "jumping out from the normal flow"
If you find yourself in a situation that you write this Exception "remapping" logic again and again
then make the to-be-decorated method private and expose the "remapping" logic as public
public Result XYZ(){varresult= whateverPolicy.ExecuteAndCapture(XYZCore);if(result.Outcome != OutcomeType.Successful && result.FinalExecption is HttpRequestException)thrownew CustomNetworkException(result.FinalExecption);
...}private Result XYZCore(){
...}
2 - Using retry to perform fallback
Lets suppose you have a primary and a secondary endpoint. If primary fails then you want to call the secondary.
As it was discussed in this PR I try to collect those anti-patterns what I have seen in past 3+ years on StackOverflow.
In this issue I will focus only on Fallback.
1 - Using fallback to replace thrown exception
❌ DON'T
Throw custom exception from the
onFallback
Reasoning:
✅ DO
Use
ExecuteAndCapture
and thenFinalException
Reasoning:
private
and expose the "remapping" logic aspublic
2 - Using retry to perform fallback
Lets suppose you have a primary and a secondary endpoint. If primary fails then you want to call the secondary.
❌ DON'T
Use retry to perform fallback
Reasoning:
n
timesn
is the initial attempt +retryCount
so, in this case it means 2✅ DO
Use fallback to call secondary
Reasoning:
Context
orExecuteAndCapture
)3 - Nesting
ExecuteAsync
callsThere are many ways to combine multiple policies together. One of the least desired one is the
Execute
hellNOTE: This is not strictly related to Fallback but I've seen it many times when Fallback was the most outer.
❌ DON'T
Nest
ExecuteAsync
callsReasoning:
CancellationToken
parameter✅ DO
Use
PolicyWrap
to chain themReasoning:
CancellationToken
s are propagated between the policies automatically on your behalfThe text was updated successfully, but these errors were encountered: