Remora / Remora.Results

A simple, versatile algebraic data type for C#.
GNU Lesser General Public License v3.0
15 stars 5 forks source link

Add Result<T>.OrThrow() #18

Open Foxtrek64 opened 4 months ago

Foxtrek64 commented 4 months ago

Sometimes you just need an exception, even if avoiding them is a goal of this library. Examples include situations where you are defining a custom type that has Parse() and TryParse() methods that both point to a common method returning Result<T>.

Currently it is possible to accomplish something similar to the proposed OrThrow() function by doing the following:

public static Foo TryParse(string value)
{
    Result<Foo> parseResult = TryParseResult(value);

    return parseResult.MapOrElse
    (
        it => it,
        (error, _) => throw new Exception(...)
    );
}

This feels like an abuse of the Map part of the MapOrElse() pattern. Returning itself is not the intended use.

So I'd like to propose the following, which does exactly the same thing as above but with better semantics:

public TEntity OrThrow<TException>(func<IResultError, IResult?, TException> exceptionFactory)
    where TException : Exception
{
    return this.IsSuccess
        ? this.Entity
        : exceptionFactory(this.Error, this.Inner);
}

Example usage:

public static Foo TryParse(string value)
{
    Result<Foo> parseResult = TryParseResult(value);

    return parseResult.OrThrow((error, _) => throw new Exception(...));
}