From e14afd10638f32d0e859e9df52872ad59cdc7931 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franti=C5=A1ek=20Boh=C3=A1=C4=8Dek?= Date: Tue, 21 Dec 2021 21:58:13 +0100 Subject: [PATCH] feat: add logging extension for results --- .../Extensions/ResultExtensions.cs | 67 +++++++++++++++++++ Core/NosSmooth.Core/NosSmooth.Core.csproj | 1 + 2 files changed, 68 insertions(+) create mode 100644 Core/NosSmooth.Core/Extensions/ResultExtensions.cs diff --git a/Core/NosSmooth.Core/Extensions/ResultExtensions.cs b/Core/NosSmooth.Core/Extensions/ResultExtensions.cs new file mode 100644 index 0000000..41c2dae --- /dev/null +++ b/Core/NosSmooth.Core/Extensions/ResultExtensions.cs @@ -0,0 +1,67 @@ +// +// ResultExtensions.cs +// +// Copyright (c) František Boháček. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Text; +using Microsoft.Extensions.Logging; +using Remora.Results; + +namespace NosSmooth.Core.Extensions; + +/// +/// Contains extension methods for . +/// +public static class ResultExtensions +{ + /// + /// Logs the given result if it is errorful. + /// + /// The logger. + /// The result to log. + /// Thrown if the result was unsuccessful. + public static void LogResultError(this ILogger logger, IResult result) + { + if (result.IsSuccess) + { + throw new InvalidOperationException("The result was successful, it has to be unsuccessful to log it."); + } + + switch (result.Error) + { + case AggregateError aggregateError: + logger.LogAggreggateError(aggregateError); + break; + default: + logger.LogNestedError(result); + break; + } + } + + private static void LogAggreggateError(this ILogger logger, AggregateError error) + { + foreach (var result in error.Errors) + { + logger.LogResultError(result); + } + } + + private static void LogNestedError(this ILogger logger, IResult? result) + { + if ((result?.IsSuccess ?? true) || result.Error is null) + { + throw new InvalidOperationException("The result was successful, it has to be unsuccessful to log it."); + } + + var stringBuilder = new StringBuilder(result.Error.Message); + int index = 0; + while ((result = result?.Inner) is not null && result.Error is not null) + { + stringBuilder.Append($"\n {index++}: {result.Error.Message}"); + } + + logger.LogError(stringBuilder.ToString()); + } +} \ No newline at end of file diff --git a/Core/NosSmooth.Core/NosSmooth.Core.csproj b/Core/NosSmooth.Core/NosSmooth.Core.csproj index eb756c8..f79deb2 100644 --- a/Core/NosSmooth.Core/NosSmooth.Core.csproj +++ b/Core/NosSmooth.Core/NosSmooth.Core.csproj @@ -7,6 +7,7 @@ + -- 2.48.1