Innovenergy_trunk/csharp/Lib/Utils/Try/TrySync.async.cs

107 lines
2.2 KiB
C#

namespace InnovEnergy.Lib.Utils.Try;
public partial class TrySync<R>
{
public TryAsync<R> OnError<E>(Func<E, Task<R>> onError) where E:Exception
{
async Task<R> TryIt()
{
try
{
return Func();
}
catch (E e)
{
return await onError(e);
}
}
return new TryAsync<R>(TryIt!);
}
public TryAsync<R> OnError<E>(Func<E, Func<R>, Task<R>> onError) where E : Exception
{
async Task<R> TryIt()
{
try
{
return 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 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 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 = 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 = Throw();
return await map(r);
}
return new TryAsync<S>(MapIt);
}
public TryAsync<S> Block<S>(Func<TrySync<R>, TryAsync<S>> map)
{
return map(this);
}
}