From d9cc716df5adf4d3db0be66e2e21e0e6d3ed66e5 Mon Sep 17 00:00:00 2001 From: Rutherther Date: Sat, 19 Feb 2022 14:00:40 +0100 Subject: [PATCH] feat(core): handle exceptions in command processor --- .../Commands/CommandProcessor.cs | 89 ++++++++++++------- 1 file changed, 56 insertions(+), 33 deletions(-) diff --git a/Core/NosSmooth.Core/Commands/CommandProcessor.cs b/Core/NosSmooth.Core/Commands/CommandProcessor.cs index 4392aa3..31c7eb9 100644 --- a/Core/NosSmooth.Core/Commands/CommandProcessor.cs +++ b/Core/NosSmooth.Core/Commands/CommandProcessor.cs @@ -97,7 +97,16 @@ public class CommandProcessor return result; } - var handlerResult = await commandHandler.HandleCommand(command, ct); + Result handlerResult; + try + { + handlerResult = await commandHandler.HandleCommand(command, ct); + } + catch (Exception e) + { + handlerResult = e; + } + var afterResult = await ExecuteAfterExecutionAsync ( scope.ServiceProvider, @@ -129,27 +138,34 @@ public class CommandProcessor ) where TCommand : ICommand { - var results = await Task.WhenAll - ( - services.GetServices() - .Select(x => x.ExecuteBeforeCommandAsync(client, command, ct)) - ); - - var errorResults = new List(); - foreach (var result in results) + try { - if (!result.IsSuccess) + var results = await Task.WhenAll + ( + services.GetServices() + .Select(x => x.ExecuteBeforeCommandAsync(client, command, ct)) + ); + + var errorResults = new List(); + foreach (var result in results) { - errorResults.Add(result); + if (!result.IsSuccess) + { + errorResults.Add(result); + } } - } - return errorResults.Count switch + return errorResults.Count switch + { + 1 => errorResults[0], + 0 => Result.FromSuccess(), + _ => new AggregateError(errorResults.Cast().ToArray()) + }; + } + catch (Exception e) { - 1 => errorResults[0], - 0 => Result.FromSuccess(), - _ => new AggregateError(errorResults.Cast().ToArray()) - }; + return e; + } } private async Task ExecuteAfterExecutionAsync @@ -162,26 +178,33 @@ public class CommandProcessor ) where TCommand : ICommand { - var results = await Task.WhenAll - ( - services.GetServices() - .Select(x => x.ExecuteAfterCommandAsync(client, command, handlerResult, ct)) - ); - - var errorResults = new List(); - foreach (var result in results) + try { - if (!result.IsSuccess) + var results = await Task.WhenAll + ( + services.GetServices() + .Select(x => x.ExecuteAfterCommandAsync(client, command, handlerResult, ct)) + ); + + var errorResults = new List(); + foreach (var result in results) { - errorResults.Add(result); + if (!result.IsSuccess) + { + errorResults.Add(result); + } } - } - return errorResults.Count switch + return errorResults.Count switch + { + 1 => errorResults[0], + 0 => Result.FromSuccess(), + _ => new AggregateError(errorResults.Cast().ToArray()) + }; + } + catch (Exception e) { - 1 => errorResults[0], - 0 => Result.FromSuccess(), - _ => new AggregateError(errorResults.Cast().ToArray()) - }; + return e; + } } } \ No newline at end of file -- 2.49.0