How can I capture Exception from Circuitbreaker (Polly) and generate a log?

Asked

Viewed 43 times

0

I’m trying to capture through Action onBreak, but apparently it never launches Exception on screen.

using Polly;
using System;
using System.Collections.Generic;

namespace CircuitBreakingPolly
{
    public class Program
    {
        public static int n1 = 2;
        public static int n2 = 0;

        private static List<Produtos> produtos = new List<Produtos>();
        static void Main(string[] args)
        {
            var result = Execute(() => Divisao(n1, n2), () => Divisao(2, 2));
            Console.WriteLine(result.ToString());

            Console.ReadKey();
        }

        public static TResult Execute<TResult, TReset>(Func<TResult> action, Func<TReset> actionReset)
        {

            return Policy
                .Handle<DivideByZeroException>()
                .CircuitBreaker(4, TimeSpan.FromMinutes(1), onBreak: (exception, timespan, context) =>
                {
                    Console.Write(exception.Message, timespan);
                }
                , onReset: (context) =>
                {
                    actionReset.Invoke();
                }
                , onHalfOpen: () =>
                {
                    actionReset.Invoke();
                })
                .Execute(action);
        }


        private static int Divisao(int n1, int n2)
        {
            return n1 / n2;
        }


        internal static void AtualizarNumero(Exception e, int n)
        {
            n2 = n;
            PoliticasManipulacaoPolly.Log(e);
        }
    }
}

1 answer

0

I discovered that the Circuitbreaker does not work by itself, it is necessary to combine it with another policy like Retry.

In my case it’s like this.

public Task ExecuteCircuitBreaker(Func<Task> action)
        {
            //Program.programStartTime = DateTime.Now;
            // simular o erro
            Program.programStartTime = DateTime.Now.AddSeconds(10);

            int totalvezes = 2;
            Task result2 = null;

            //Thread safety
            //PolicyWrap is thread - safe: multiple calls may safely be placed concurrently through a policy instance.
            //Policy reuse
            //PolicyWrap instances may be re - used across multiple call sites.
            //When reusing policies, use an ExecutionKey to distinguish different call - site usages within logging and metrics.

            Policy retryPolicy = Policy.Handle<TimeoutException>().RetryAsync(totalvezes);

            Policy circuitBreakerPolicy = Policy
                .Handle<TimeoutException>()
                .CircuitBreakerAsync(totalvezes, TimeSpan.FromSeconds(2));

            try
            {
                // you need to combine retry policy with circuit breaker policy. One way to do that would be:
                result2 = retryPolicy.ExecuteAsync(() => circuitBreakerPolicy.ExecuteAsync(action, true));

                // or Polly has also now added PolicyWrap which can make the syntax for
                //combining policies even more concise:

                //result2 = retryPolicy.WrapAsync(circuitBreakerPolicy).ExecuteAsync(action, true);
            }
            catch (AggregateException ex)
            {
                Log(ex);
            }
            catch (Exception ex)
            {
                Log(ex);
            }

            return result2;
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.