103 lines
2.0 KiB
C#
103 lines
2.0 KiB
C#
|
namespace InnovEnergy.Lib.Utils.Try;
|
||
|
|
||
|
public partial class TryAsync<R>
|
||
|
{
|
||
|
public TryAsync<R> OnError<E>(Func<E, R> onError) where E : Exception
|
||
|
{
|
||
|
async Task<R> TryIt()
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
return await Func();
|
||
|
}
|
||
|
catch (E e)
|
||
|
{
|
||
|
return onError(e);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return new TryAsync<R>(TryIt);
|
||
|
}
|
||
|
|
||
|
public TryAsync<R> OnError<E>(Func<E, Func<Task<R>>, R> onError) where E : Exception
|
||
|
{
|
||
|
async Task<R> TryIt()
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
return await Func();
|
||
|
}
|
||
|
catch (E e)
|
||
|
{
|
||
|
return onError(e, Func);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return new TryAsync<R>(TryIt);
|
||
|
}
|
||
|
|
||
|
public TryAsync<R> Retry<E>(Func<E, Boolean> shouldRetry) where E : Exception
|
||
|
{
|
||
|
async Task<R> TryIt()
|
||
|
{
|
||
|
while(true)
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
return await Func();
|
||
|
}
|
||
|
catch (E e)
|
||
|
{
|
||
|
if (!shouldRetry(e))
|
||
|
throw;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return new TryAsync<R>(TryIt);
|
||
|
}
|
||
|
|
||
|
public TryAsync<R> OnErrorDo<E>(Action<E> onError) where E:Exception
|
||
|
{
|
||
|
async Task<R> TryIt()
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
return await Func();
|
||
|
}
|
||
|
catch (E e)
|
||
|
{
|
||
|
onError(e);
|
||
|
throw;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return new TryAsync<R>(TryIt);
|
||
|
}
|
||
|
|
||
|
public TryAsync<R> OnSuccessDo(Action<R> onSuccess)
|
||
|
{
|
||
|
async Task<R> DoIt()
|
||
|
{
|
||
|
var result = await Func();
|
||
|
onSuccess(result);
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
return new TryAsync<R>(DoIt);
|
||
|
}
|
||
|
|
||
|
public TryAsync<S> ThenTry<S>(Func<R, S> map)
|
||
|
{
|
||
|
async Task<S> MapIt()
|
||
|
{
|
||
|
var r = await Throw();
|
||
|
return map(r);
|
||
|
}
|
||
|
|
||
|
return new TryAsync<S>(MapIt);
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
}
|