Skip to content

Commit

Permalink
Add ability to retrieve error values from either
Browse files Browse the repository at this point in the history
  • Loading branch information
khanage committed Oct 1, 2024
1 parent ea8a6a6 commit a04d68d
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Bearded.Monads/EitherExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,20 @@ public static Either<A, NewError> MapError<A, Error, NewError>(this Either<A, Er
return either.AsSuccess.Value;
}

public static E ElseError<A,E>(this Either<A,E> either, E error) {
if (either.IsSuccess)
return error;

return either.AsError.Value;
}

public static E ElseErrorOrThrow<A,E>(this Either<A,E> either) {
if (either.IsSuccess)
throw new ValueWasPresentWhenNotExpectedException(either.AsSuccess.Value);

return either.AsError.Value;
}

public static Either<A, Error> Flatten<A, Error>(
this Either<Either<A, Error>, Error> ee)
=> ee.SelectMany(id);
Expand All @@ -166,5 +180,14 @@ public static Either<IEnumerable<A>, Error> Sequence<A, Error>(
public static Either<A, Error> WhereNot<A, Error>(this Either<A, Error> incoming,
Predicate<A> notPredicate, Func<Error> errorCallback)
=> incoming.Where(x => !notPredicate(x), errorCallback);

[Serializable]
private class ValueWasPresentWhenNotExpectedException : Exception
{
public ValueWasPresentWhenNotExpectedException(object value)
: base($"Expected an unsuccesful call, but found ${value}")
{
}
}
}
}

0 comments on commit a04d68d

Please sign in to comment.