public async Task ExecuteCommandHandlerAsync <TCommand>(IDispatcher dispatcher, ICommandContext <TCommand> context, Type handlerType) where TCommand : class, ICommand { using (var scope = _serviceProvider.CreateScope()) { try { if (scope.ServiceProvider.GetService(handlerType) is ICommandHandler <TCommand> handler) { await handler.HandleAsync(dispatcher, context).ConfigureAwait(false); await _engine.NotifySuccessAsync(context.Message).ConfigureAwait(false); } else { throw new MissingHandlerException(handlerType, $"No valid registration for {handlerType.FullName}"); } } catch (MissingHandlerException ex) { _logger.LogError(new { eventType = typeof(TCommand), ex.HandlerType }, ex, (s, e) => $"No valid registration for {s.HandlerType.FullName}"); throw; } catch (Exception ex) { var message = context.Message as CommandMessage <TCommand>; _logger.LogError(new { CorrelationId = context.CorrelationId, MessageId = context.Message.MessageId, EventType = typeof(TCommand).Name, Message = message }, ex, (s, e) => $"An error occurred while handling {s.EventType}. {e.Message}"); await HandleCommandErrorAsync(context, ex).ConfigureAwait(false); } } }
public async Task HandleErrorAsync <TCommand>(ICommandContext <TCommand> context, Exception exception, CommandErrorDelegate <TCommand> next) where TCommand : class, ICommand { if (context.Message is CommandMessage <TCommand> message) { var retryCount = RetryCount(message) + 1; if (retryCount < _options.MaxRetries) { _logger.LogTrace($"Error {retryCount}/{_options.MaxRetries}: will retry"); message.Headers[Headers.RetryCount] = retryCount.Stringfy(); await _engine.NotifySuccessAsync(message).ConfigureAwait(false); await _engine.SendMessageAsync(message).ConfigureAwait(false); } else { _logger.LogTrace($"Error {retryCount}/{_options.MaxRetries}: will not retry"); //await _engine.NotifyFailAsync(message).ConfigureAwait(false); await next(context, exception).ConfigureAwait(false); } } }