using DigitalData.Core.Exceptions;
namespace EnvelopeGenerator.Application.Common.Extensions;
///
/// Extension methods for tasks
///
public static class TaskExtensions
{
///
/// Awaits the specified task and ensures that the result is not null.
/// If the result is null, the exception created by factory-method is thrown.
///
/// The type of the result.
/// The type of the exception.
/// The task to await.
/// Exception provider
/// The awaited result if not null.
/// Thrown if the result is null.
public static async Task ThrowIfNull(this Task task, Func factory) where TException : Exception
{
var result = await task;
return result ?? throw factory();
}
///
/// Awaits the specified task and ensures that the result is not empty.
/// If the result contains no elements, the exception created by factory-method is thrown.
///
/// The element type of the collection.
/// The type of the exception.
/// The task to await.
/// Exception provider
/// The awaited collection if it is not null or empty.
/// Thrown if the result is null or empty.
public static async Task> ThrowIfEmpty(this Task> task, Func factory) where TException : Exception
{
var result = await task;
return result?.Any() ?? false ? result : throw factory();
}
///
///
///
///
///
///
///
///
public static async Task Then(this Task task, Func act)
{
var res = await task;
return act(res);
}
}
///
///
///
public static class Exceptions
{
///
///
///
public static NotFoundException NotFound() => new();
///
///
///
///
public static BadRequestException BadRequest() => new();
///
///
///
///
public static ForbiddenException Forbidden() => new();
}