Fluent Validation Custom response using pipeline behavior

Viewed 27

I have a MediatR Pipeline behavior for validating commands with the FluentValidation library. All the examples that I came across were throwing ValidationException if any failures happening, instead of doing that I want to return the response with the error.

Here I want to have response model

[{
errorMesages:[]
status:404
ErrorField:propertyName

}]

public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
  private readonly IEnumerable<IValidator<TRequest>> _validators;

  public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators)
  {
      _validators = validators;
  }

  public  Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
  {
      var failures = _validators
         .Select(v => v.Validate(request))
         .SelectMany(result => result.Errors)
         .Where(f => f != null)
         .ToList();

      if (failures.Any())
      {
          throw new ValidationException(failures);
      }

      return next();
   }

       
}
1 Answers

try use this instead

public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        if (_validators.Any())
        {
            var context = new ValidationContext<TRequest>(request);
            var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
            var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();
            if (failures.Count != 0)
                throw new FluentValidation.ValidationException(failures);
        }
        return await next();
    }
Related