Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Result<T>.OrThrow() #18

Open
Foxtrek64 opened this issue Jun 7, 2024 · 0 comments
Open

Add Result<T>.OrThrow() #18

Foxtrek64 opened this issue Jun 7, 2024 · 0 comments

Comments

@Foxtrek64
Copy link
Contributor

Foxtrek64 commented Jun 7, 2024

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(...));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant