From 043228dddfa9f30b46b6b74f6d3b915857b53beb Mon Sep 17 00:00:00 2001 From: Gregory Nickonov Date: Sun, 7 Dec 2025 22:40:01 +0300 Subject: [PATCH] feat: Add `MapError` method for transforming errors in `Result` - Introduce `MapError` to `Result` for converting errors using a mapping function. - Add async `MapError` extension in `TaskResultExtensions` for handling errors in asynchronous contexts. --- src/Digillect.FP.Types/Result.cs | 17 +++++++++++++++++ src/Digillect.FP.Types/TaskResultExtensions.cs | 15 +++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/Digillect.FP.Types/Result.cs b/src/Digillect.FP.Types/Result.cs index d0bb284..4e2b4d9 100644 --- a/src/Digillect.FP.Types/Result.cs +++ b/src/Digillect.FP.Types/Result.cs @@ -120,6 +120,23 @@ public async Task> MapAsync(Func> map) return Result.Success(result); } + /// + /// Converts the error of the current result into a new error using the specified mapping function. + /// + /// A function to transform the current error into a new error. + /// A result with the current value and the transformed error. + public Result MapError(Func mapError) + { + if (_error is null) + { + return this; + } + + var error = mapError(_error); + + return Result.Error(error); + } + /// /// Chains the successful result to another operation that returns a using the provided binding function. /// diff --git a/src/Digillect.FP.Types/TaskResultExtensions.cs b/src/Digillect.FP.Types/TaskResultExtensions.cs index cc74fdb..ca97593 100644 --- a/src/Digillect.FP.Types/TaskResultExtensions.cs +++ b/src/Digillect.FP.Types/TaskResultExtensions.cs @@ -53,6 +53,21 @@ public static async Task> Map(this Task> r return awaitedResult.Map(map); } + /// + /// Maps an error from a failed into a new with the transformed error value. + /// + /// The type of the value contained in the original result. + /// The original result to map the error from. + /// A function to transform the error from the original result to the new error type. + /// + /// A new that contains either the original success value or the transformed error. + /// + public static async Task> MapError(this Task> result, Func mapError) + { + var awaitedResult = await result.ConfigureAwait(false); + return awaitedResult.MapError(mapError); + } + /// /// Transforms the success value of the current asynchronous instance using the specified /// asynchronous mapping function .