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.
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
using System.Collections;
|
||||
using DigitalData.Core.Exceptions;
|
||||
using MediatR;
|
||||
|
||||
namespace EnvelopeGenerator.Application.Common.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for <see cref="IMediator"/> that enforce non-null and non-empty responses.
|
||||
/// </summary>
|
||||
public static class MediatorExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Sends a request via MediatR and throws <see cref="NotFoundException"/> when the response is <c>null</c> or an empty collection.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected response type.</typeparam>
|
||||
/// <param name="mediator">The mediator instance.</param>
|
||||
/// <param name="request">The MediatR request whose response may be <c>null</c>.</param>
|
||||
/// <param name="exceptionMessage">Optional message for the <see cref="NotFoundException"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A guaranteed non-null <typeparamref name="TResponse"/>.</returns>
|
||||
/// <exception cref="NotFoundException">Thrown when the response is <c>null</c> or an empty collection.</exception>
|
||||
public static async Task<TResponse> SendOrNotFoundAsync<TResponse>(this IMediator mediator, IRequest<TResponse?> request, string? exceptionMessage, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if(await mediator.Send(request, cancellationToken) is TResponse res)
|
||||
{
|
||||
if(res is IEnumerable enumerable && !enumerable.Cast<object>().Any())
|
||||
throw new NotFoundException(exceptionMessage);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
throw new NotFoundException(exceptionMessage);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="SendOrNotFoundAsync{TResponse}(IMediator, IRequest{TResponse}, string, CancellationToken)"/>
|
||||
public static async Task<TResponse> SendOrNotFoundAsync<TResponse>(this IMediator mediator, IRequest<TResponse?> request, CancellationToken cancellationToken = default)
|
||||
=> await mediator.SendOrNotFoundAsync(request, null, cancellationToken);
|
||||
}
|
||||
Reference in New Issue
Block a user