Innovenergy_trunk/csharp/lib/Utils/Try/TryAsync.async.cs

107 lines
2.2 KiB
C#
Raw Normal View History

2023-02-16 12:57:06 +00:00
namespace InnovEnergy.Lib.Utils.Try;
public partial class TryAsync<R>
{
public TryAsync<R> OnError<E>(Func<E, Task<R>> onError) where E:Exception
{
async Task<R> TryIt()
{
try
{
return await Func();
}
catch (E e)
{
return await onError(e);
}
}
return new TryAsync<R>(TryIt);
}
public TryAsync<R> OnError<E>(Func<E, Func<Task<R>>, Task<R>> onError) where E : Exception
{
async Task<R> TryIt()
{
try
{
return await Func();
}
catch (E e)
{
return await onError(e, Func);
}
}
return new TryAsync<R>(TryIt);
}
public TryAsync<R> Retry<E>(Func<E, Task<Boolean>> shouldRetry) where E:Exception
{
async Task<R> TryIt()
{
while(true)
{
try
{
return await Func();
}
catch (E e)
{
if (! await shouldRetry(e))
throw;
}
}
}
return new TryAsync<R>(TryIt);
}
public TryAsync<R> OnErrorDo<E>(Func<E, Task> onError) where E:Exception
{
async Task<R> TryIt()
{
try
{
return await Func();
}
catch (E e)
{
await onError(e);
throw;
}
}
return new TryAsync<R>(TryIt);
}
public TryAsync<R> OnSuccessDo(Func<R, Task> onSuccess)
{
async Task<R> DoIt()
{
var result = await Func();
await onSuccess(result);
return result;
}
return new TryAsync<R>(DoIt);
}
public TryAsync<S> ThenTry<S>(Func<R, Task<S>> map)
{
async Task<S> MapIt()
{
var r = await Throw();
return await map(r);
}
return new TryAsync<S>(MapIt);
}
public TryAsync<S> Block<S>(Func<TryAsync<R>, TryAsync<S>> map)
{
return map(this);
}
}