我们正在使用 CQRS 模式,并且在流式验证的错误处理方面存在问题。(CQRS 模式 @ https://lostechies.com/jimmybogard/2015/05/05/cqrs-with-mediatr-and-automapper/)
public class OtherSpecified : AbstractValidator<Command>
{
public OtherSpecified(ApplicationDbContext context)
{
RuleFor(x => x.Other).NotNull();
}
}
public class DepartmentSpecified : AbstractValidator<Command>
{
public DepartmentSpecified(ApplicationDbContext context)
{
RuleFor(x => x.Department).NotNull();
}
}
现在我们注入我们的验证处理程序,以便我们可以根据来自http://lostechies.com/jimmybogard/2014/09/09/tackling-cross-cutting-concerns-with-a-mediator-pipeline/的信息运行多个抽象验证器。这可行,但因为我可以看到在 foreach 循环中运行的规则
public TResponse Handle(TRequest request)
{
var context = new ValidationContext(request);
var result = new ValidationResult();
var list = _validators.ToList();
foreach (var validator in list)
{
var results = validator.Validate(request);
foreach (var validationFailure in results.Errors)
{
result.Errors.Add(validationFailure);
//temp testing code below
if (results.Errors.Count > 0)
throw new ValidationException(result.Errors);
}
}
if (result.Errors != null &&
result.Errors.Count > 0)
{
throw new ValidationException(result.Errors);
}
return _inner.Handle(request);
}
问题是未处理流畅的验证异常( ValidationException )。规则错误冒泡为
说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:FluentValidation.ValidationException:验证失败:
我期望的是流利的验证来处理错误并将其作为验证错误传递回 json 中的 ajax 请求