Skip to content

Instantly share code, notes, and snippets.

@zsmahi
Last active July 30, 2023 09:42
Show Gist options
  • Save zsmahi/3e936893050ba740812eed63be9c3d77 to your computer and use it in GitHub Desktop.
Save zsmahi/3e936893050ba740812eed63be9c3d77 to your computer and use it in GitHub Desktop.
Extension method to chain Tasks in the Promise Way Then-Catch
using System;
using System.Threading.Tasks;
namespace Library.CustomExtensions
{
public static class TaskExtensions
{
public static async Task<TOut> Then<TIn, TOut>(
this Task<TIn> task,
Func<TIn, Task<TOut>> continuation,
CancellationToken cancellationToken = default
)
{
if (task == null)
{
throw new ArgumentNullException(nameof(task));
}
if (continuation == null)
{
throw new ArgumentNullException(nameof(continuation));
}
cancellationToken.ThrowIfCancellationRequested();
TIn result = await task.ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
return await continuation(result).ConfigureAwait(false);
}
public static async Task<T> Catch<T>(
this Task<T> task,
Func<Exception, T> errorHandler,
CancellationToken cancellationToken = default
)
{
if (task == null)
{
throw new ArgumentNullException(nameof(task));
}
if (errorHandler == null)
{
throw new ArgumentNullException(nameof(errorHandler));
}
cancellationToken.ThrowIfCancellationRequested();
try
{
return await task.ConfigureAwait(false);
}
catch (Exception ex)
{
T result = errorHandler(ex);
cancellationToken.ThrowIfCancellationRequested();
return result;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment