diff --git a/EnvelopeGenerator.Application/Extensions/TaskExtensions.cs b/EnvelopeGenerator.Application/Extensions/TaskExtensions.cs new file mode 100644 index 00000000..bbb0d495 --- /dev/null +++ b/EnvelopeGenerator.Application/Extensions/TaskExtensions.cs @@ -0,0 +1,39 @@ +using EnvelopeGenerator.Application.Exceptions; + +namespace EnvelopeGenerator.Application.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, a is thrown. + /// + /// The type of the result. + /// The task to await. + /// Optional custom exception message. + /// The awaited result if not null. + /// Thrown if the result is null. + public static async Task ThrowIfNull(this Task task, string? exceptionMessage = null) + { + var result = await task; + return result ?? throw new NotFoundException(exceptionMessage); + } + + /// + /// Awaits the specified task and ensures that the result is not null or empty. + /// If the result is null or contains no elements, a is thrown. + /// + /// The element type of the collection. + /// The task to await. + /// Optional custom exception message. + /// The awaited collection if it is not null or empty. + /// Thrown if the result is null or empty. + public static async Task> ThrowIfNull(this Task?> task, string? exceptionMessage = null) + { + var result = await task; + return result?.Any() ?? false ? result : throw new NotFoundException(exceptionMessage); + } +}