Developer 02 dad43de8b1 refactor(ReadHistoryQuery): update to not throw exception.
- update controller to throw NotFound if the list is empty
2025-08-28 18:30:27 +02:00

78 lines
2.7 KiB
C#

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