From cb641fd33abf51029d13356bcbe6d75781b588e1 Mon Sep 17 00:00:00 2001 From: TekH Date: Fri, 22 Aug 2025 16:33:30 +0200 Subject: [PATCH] feat: add TaskExtensions with null and empty result checks - Introduced ThrowIfNull(Task) extension method to ensure awaited result is not null, throwing NotFoundException otherwise - Added ThrowIfNull(Task?>) extension method to validate collections, throwing NotFoundException if null or empty - Supports optional custom exception messages for better error context --- .../Extensions/TaskExtensions.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 EnvelopeGenerator.Application/Extensions/TaskExtensions.cs 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); + } +}