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(...));
}
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()
andTryParse()
methods that both point to a common method returningResult<T>
.Currently it is possible to accomplish something similar to the proposed
OrThrow()
function by doing the following:This feels like an abuse of the
Map
part of theMapOrElse()
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:
Example usage: