Failure and Fallback
Calling the Fallback Pipeline
Using the FallbackPolicy Attribute
Example with Resilience Pipelines (V10)
public class MyFallbackProtectedHandler: RequestHandler<MyCommand>
{
[FallbackPolicy(backstop: false, circuitBreaker: true, step: 1)]
[UseResiliencePipeline("MyCircuitBreakerPipeline", step: 2)]
[UseResiliencePipeline("MyRetryPipeline", step: 3)]
public override MyCommand Handle(MyCommand command)
{
// Do some work that can fail
var result = CallExternalService();
return base.Handle(command);
}
public override MyCommand Fallback(MyCommand command)
{
if (Context.Bag.ContainsKey(FallbackPolicyHandler<MyCommand>.CAUSE_OF_FALLBACK_EXCEPTION))
{
var exception = Context.Bag[FallbackPolicyHandler<MyCommand>.CAUSE_OF_FALLBACK_EXCEPTION] as Exception;
// Log the failure
_logger.LogError(exception, "Handler failed, executing fallback");
// Take compensating action
if (exception is BrokenCircuitException)
{
// Circuit breaker is open, queue for later retry
_messageQueue.QueueForRetry(command);
}
else
{
// Other failure, send compensating transaction
_commandProcessor.Send(new UndoCommand { OriginalCommandId = command.Id });
}
}
return base.Fallback(command);
}
}Example with Legacy Policies (V9)
Scope of a Fallback
Pipeline Order
Fallback Policy Options
backstop Parameter
circuitBreaker Parameter
Common Fallback Patterns
1. Compensating Transaction
2. Queue for Later Delivery
3. Default Value or Cached Response
4. Alert and Fail Gracefully
Integration with Polly Fallback Strategy
Feature
Brighter FallbackPolicy
Polly Fallback Strategy
Best Practices
Additional Resources
Last updated
Was this helpful?
