流畅的验证无法处理异常

时间:2017-09-05 17:44:55

标签: servicestack fluentvalidation

将ServiceStack升级到4.5.8后,ServiceStack会尝试Fluent Validation抛出的异常,并且只要在验证程序中抛出异常,就会通过验证而不是失败。这似乎只在正在运行的验证程序使用SetValidator方法时发生。

这将返回新用户,而不是返回错误消息" Validator Exception"。

验证

public class SaveUserValidator : AbstractValidator<SaveUser>
{
    public SaveUserValidator()
    {
        this.CascadeMode = CascadeMode.StopOnFirstFailure;

        RuleFor(x => x.Id)
            .Must(ThrowException);

        RuleFor(x => x.User)
            .SetValidator(new UserValidator());
    }

    private bool ThrowException(int arg)
    {
        throw new ApplicationException("Validator Exception");
    }
}

UserValidator

public class UserValidator : AbstractValidator<User>
{
    public UserValidator()
    {
        this.CascadeMode = CascadeMode.StopOnFirstFailure;

        RuleFor(x => x.Name).NotEmpty();
    }
}

用户

public class User
{
    public string Name { get; set; }
}

SaveUser

public class SaveUser
{
    public int Id { get; set; }

    public User User { get; set; }
}

UserService

public class UserService : Service
{
    public IHttpResult Post(SaveUser request)
    {
        return new HttpResult(new SaveUser { Id = -100, User = new User { Name = "bad name" } }, HttpStatusCode.Created);
    }
}

1 个答案:

答案 0 :(得分:1)

ServiceStack升级为使用v4.5.8中的latest version of FluentValidation,发布说明中列出的更改之一因Fluent验证而更改,因为previus版本必须明确指定不应为null的属性,因此UserValidator应更改为:

RuleFor(x => x.User)
    .NotEmpty()
    .SetValidator(new UserValidator());

吞噬异常的问题是由于ChildValidatorAdaptor被异步并且抛出的异常未被处理,因为如果属性验证具有Must()之类的验证异常应该返回boolean失败了,例如:

RuleFor(x => x.Id)
    .Must(id => false);

不抛出异常,但我刚刚添加了对处理this commit中验证器中抛出的异常的支持。此更改可从v4.5.13获得,现在为available on MyGet

相关问题