From 9ad4352e02f20e6094d220e17adc61d030b4179c Mon Sep 17 00:00:00 2001 From: TekH Date: Wed, 8 Apr 2026 13:25:34 +0200 Subject: [PATCH] Add MediatorExtensions for not-found handling in MediatR Introduced MediatorExtensions with SendOrNotFoundAsync methods to enforce non-null and non-empty responses from MediatR requests. These extensions throw NotFoundException when responses are null or empty, centralizing not-found logic and improving error handling. --- .../Common/Extensions/MediatorExtensions.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 EnvelopeGenerator.Application/Common/Extensions/MediatorExtensions.cs diff --git a/EnvelopeGenerator.Application/Common/Extensions/MediatorExtensions.cs b/EnvelopeGenerator.Application/Common/Extensions/MediatorExtensions.cs new file mode 100644 index 00000000..ea971903 --- /dev/null +++ b/EnvelopeGenerator.Application/Common/Extensions/MediatorExtensions.cs @@ -0,0 +1,38 @@ +using System.Collections; +using DigitalData.Core.Exceptions; +using MediatR; + +namespace EnvelopeGenerator.Application.Common.Extensions; + +/// +/// Extension methods for that enforce non-null and non-empty responses. +/// +public static class MediatorExtensions +{ + /// + /// Sends a request via MediatR and throws when the response is null or an empty collection. + /// + /// The expected response type. + /// The mediator instance. + /// The MediatR request whose response may be null. + /// Optional message for the . + /// Cancellation token. + /// A guaranteed non-null . + /// Thrown when the response is null or an empty collection. + public static async Task SendOrNotFoundAsync(this IMediator mediator, IRequest request, string? exceptionMessage, CancellationToken cancellationToken = default) + { + if(await mediator.Send(request, cancellationToken) is TResponse res) + { + if(res is IEnumerable enumerable && !enumerable.Cast().Any()) + throw new NotFoundException(exceptionMessage); + + return res; + } + + throw new NotFoundException(exceptionMessage); + } + + /// + public static async Task SendOrNotFoundAsync(this IMediator mediator, IRequest request, CancellationToken cancellationToken = default) + => await mediator.SendOrNotFoundAsync(request, null, cancellationToken); +} \ No newline at end of file