2

The end outcome is to shut down the application if a specific type of exception (DatabaseException) has occurred.

However the current method HandleDatabaseException does not stop the application, the execution will carry on. Even though the _applicationLifetime.Stop() is executed.

private IHostApplicationLifetime _applicationLifetime;

public void CreatePolcy() 
{
    var policy = Policy
                .Handle<DatabaseException>(ex => HandleDatabaseException(ex))
                .WaitAndRetryForever(
                    retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                    (exception, timespan) => HandleRetry(exception, timespan, stoppingToken));
}

public bool HandleDatabaseException(Exception ex) 
{
   _applicationLifetime.Stop();

   return true;
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
DrExpresso
  • 73
  • 1
  • 7
  • `HandleDatabaseException` should be used for filtering, not for taking actions. – Peter Csala Jul 08 '21 at 06:43
  • 1
    If you want to stop the application whenever you receive a `DatabaseException` then you should consider to use [Fallback policy](https://github.com/App-vNext/Polly/wiki/Fallback) instead. – Peter Csala Jul 08 '21 at 06:44
  • Did you manage to solve your problem with Fallback? – Peter Csala Jul 12 '21 at 07:50
  • 1
    Yes using Polly .net examples I created two policies. One was a fall-back policy which contained the HandleDatabaseException and another retry policy. Then wrapped retry inside the fallback (very important ordering or it will not work) [https://github.com/App-vNext/Polly-Samples/blob/master/PollyDemos/Sync/Demo09_Wrap-Fallback-Timeout-WaitAndRetry.cs] – DrExpresso Jul 19 '21 at 13:20
  • 1
    Yes ordering does matter. To make thing simpler you should consider to use [Policy.Wrap](https://github.com/App-vNext/Polly/wiki/PolicyWrap) : `Policy.Wrap(fallbackPolicy, retryPolicy)` – Peter Csala Jul 19 '21 at 13:30
  • Please post an anwser where you detail your solution and mark it as **the** answer – Peter Csala Jul 27 '22 at 09:53

0 Answers0