Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Política de Polly para registrar excepciones y volver a lanzar

Considero usar Polly para crear una política para registrar la excepción y volver a lanzar. No encontré un método existente que lo permita listo para usar, pero algunas opciones que veo son

Retroceder

 // Specify a substitute value or func, calling an action (eg for logging) // if the fallback is invoked. Policy.Handle<Whatever>() .Fallback<UserAvatar>(UserAvatar.Blank, onFallback: (exception, context) => { _logger.Log(exception, context); throw exception; });

Pregunta: ¿Está bien lanzar una excepción desde Fallback?

Se acabó el tiempo

 Policy.Timeout(1, T30meoutStrategy.Pessimistic, (context, timespan, task) => { // ContinueWith important!: the abandoned task may very well still be executing, // when the caller times out on waiting for it! task.ContinueWith(t => { if (t.IsFaulted) { logger.Error(context,t.Exception); throw exception; } }); }

O reintentar

 Policy.Handle<DivideByZeroException>().Retry(0, (exception, retryCount) => { logger.Error(context,exception); throw exception; });

Pregunta: ¿Se admiten 0 reintentos?

O KISS y escribir intento/atrapar simple con lanzamiento por mi cuenta.

¿Cuál de estos métodos es mejor? ¿Cuáles son tus recomendaciones?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Si aún no tiene a Polly en la mezcla, probar/atrapar parecería lo más simple.

Si ya tiene a Polly en la mezcla, FallbackPolicy se puede reutilizar de manera segura de la manera que sugiere. El delegado onFallback y la acción o el valor alternativo no se rigen por las .Handle<>() de la Política , por lo que puede volver a generar una excepción desde dentro del delegado onFallback .

 Policy<UserAvatar>.Handle<Whatever>() .Fallback<UserAvatar>(UserAvatar.Blank, onFallback: (exception, context) => { _logger.Log(exception, context); throw exception; });

El enfoque que describe su pregunta con TimeoutPolicy solo capturaría las excepciones lanzadas por los delegados de los que la persona que llamó se había alejado anteriormente debido al tiempo de espera, y solo en TimeoutMode.Pessimistic ; no todas las excepciones.


El enfoque que describe su pregunta con .Retry(0, ...) no funcionaría. Si no se especifican reintentos, no se invocará el delegado onRetry .


Para evitar el desorden de reutilizar FallbackPolicy , también puede codificar su propia LogThenRethrowPolicy , dentro de las estructuras de Polly. Esta confirmación (que agregó la NoOpPolicy simple) ejemplifica el mínimo necesario para agregar una nueva política. Podría agregar una implementación similar a NoOpPolicy pero simplemente try { } catch { /* log; rethrow */ }


EDITAR Enero de 2019 : Polly.Contrib ahora también contiene una Polly.Contrib.LoggingPolicy que puede ayudar con esto.

over 4 years ago · Santiago Trujillo Report

0

https://github.com/App-vNext/Polly-Samples/blob/master/PollyDemos/Async/AsyncDemo02_WaitAndRetryNTimes.cs muestra que puede usar la opción onRetry: al menos para WaitAndRetryAsync. Todavía no he mirado a los demás.

 HttpPolicyExtensions .HandleTransientHttpError() .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) // exponential back-off: 2, 4, 8 etc + TimeSpan.FromMilliseconds(Jitterer.Next(0, 1000)), // plus some jitter: up to 1 second onRetry: (response, calculatedWaitDuration) => { logger.LogError($"Failed attempt. Waited for {calculatedWaitDuration}. Retrying. {response.Exception.Message} - {response.Exception.StackTrace}"); } );
over 4 years ago · Santiago Trujillo Report

0

Aquí mi solución con método genérico.

 public async Task<T> PollyRetry<T>( Func<Task<T>> action) { bool hasFallback = false; Exception ex = null; var fallbackPolicy = Policy<T>.Handle<Exception>().FallbackAsync( default(T), d => { //log final exception ex = d.Exception; hasFallback = true; return Task.FromResult(new { }); }); var retryPolicy = Policy .Handle<Exception>() .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (res, timeSpan, context) => { //log exception }); var policyResult = await fallbackPolicy.WrapAsync(retryPolicy).ExecuteAndCaptureAsync(action); if (hasFallback && ex != null) throw ex; return policyResult.Result; }

 //call service with retry logic TestResponse response = await _pollyRetryService.PollyRetry(async () => { return await _testService.Test(input); });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!