I'm using NHibernate.Validator with the Loquacious ValidationDef configuration style. For all my rules I use WithMessage to set a custom message when the value is invalid. The messages are codes that I use to lookup the correct message to display, depending on context and language.
I can get these messages when calling ValidatorEngine.Validate(entity)
, but when saving an entity with NHibernate, I get an InvalidStateException with no details on why it's invalid.
So, how can I get to my validation messages after catching an InvalidStateException thrown during an NHibernate save?
The messages are in the exception, only a method call away. You need to call GetInvalidValues() on the exception.
try
{
// Flush NHibernate to invoke event listeners
}
catch (InvalidStateException invalidStateException)
{
InvalidValue[] invalidValues = invalidStateException.GetInvalidValues();
Console.WriteLine(string.Join<InvalidValue>("\n", invalidValues));
}
The reason they did not put it directly into Message of the exception, is probably because there can be multiple validation results.