feat: add TaskExtensions with null and empty result checks
- Introduced ThrowIfNull<T>(Task<T?>) extension method to ensure awaited result is not null, throwing NotFoundException otherwise - Added ThrowIfNull<T>(Task<IEnumerable<T>?>) extension method to validate collections, throwing NotFoundException if null or empty - Supports optional custom exception messages for better error context
This commit is contained in:
39
EnvelopeGenerator.Application/Extensions/TaskExtensions.cs
Normal file
39
EnvelopeGenerator.Application/Extensions/TaskExtensions.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using EnvelopeGenerator.Application.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>, a <see cref="NotFoundException"/> is thrown.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the result.</typeparam>
|
||||
/// <param name="task">The task to await.</param>
|
||||
/// <param name="exceptionMessage">Optional custom exception message.</param>
|
||||
/// <returns>The awaited result if not <c>null</c>.</returns>
|
||||
/// <exception cref="NotFoundException">Thrown if the result is <c>null</c>.</exception>
|
||||
public static async Task<T> ThrowIfNull<T>(this Task<T?> task, string? exceptionMessage = null)
|
||||
{
|
||||
var result = await task;
|
||||
return result ?? throw new NotFoundException(exceptionMessage);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Awaits the specified task and ensures that the result is not <c>null</c> or empty.
|
||||
/// If the result is <c>null</c> or contains no elements, a <see cref="NotFoundException"/> is thrown.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The element type of the collection.</typeparam>
|
||||
/// <param name="task">The task to await.</param>
|
||||
/// <param name="exceptionMessage">Optional custom exception message.</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>> ThrowIfNull<T>(this Task<IEnumerable<T>?> task, string? exceptionMessage = null)
|
||||
{
|
||||
var result = await task;
|
||||
return result?.Any() ?? false ? result : throw new NotFoundException(exceptionMessage);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user