【发布时间】:2014-09-27 22:17:44
【问题描述】:
场景
我有一个自定义规则来验证订单的运费:
public class OrderValidator : BaseValidator<Order>
{
private string CustomInfo { get; set; }
public OrderValidator()
{
//here I call the custom validation method and I try to add the CustomInfo string in the message
RuleFor(order => order.ShippingCost).Cascade(CascadeMode.StopOnFirstFailure).NotNull().Must(
(order, shippingCost) => CheckOrderShippingCost(order, shippingCost)
).WithMessage("{PropertyName} not set or not correct: {PropertyValue}." + (String.IsNullOrEmpty(CustomInfo) ? "" : " " + CustomInfo));
}
//this is the custom validation method
private bool CheckOrderShippingCost(Order o, decimal shippingCost)
{
bool res = false;
try
{
/*
* check the actual shippingCost and set the res value
*/
}
catch (Exception ex)
{
CustomInfo = ex.ToString();
res = false;
}
return res;
}
}
如果出现异常,我将异常信息存储到 CustomInfo 私有成员中,并将其添加到验证消息中。
然后我运行验证器:
OrderValidator oVal = new OrderValidator();
oVal.Results = oVal.Validate(order);
if (!oVal.Results.IsValid)
oVal.Results.Errors.ForEach(delegate(ValidationFailure error) {
Console.WriteLine(error.ErrorMessage);
});
问题
一切正常,万一发生异常,CustomInfo 被正确设置为 ex.ToString() 值。但最终在控制台中显示的错误消息并没有显示 CustomInfo,而只显示了消息的第一部分:
"Shipping Cost not set or not correct: 5.9"
问题
为什么自定义消息不包含 CustomInfo 字符串? 是否可以通过其他方式在自定义消息中添加异常信息?
【问题讨论】:
标签: c# fluentvalidation custom-errors