Validation Exceptions

Validators will throw a ValidationAspects.ValidationException or a more specific exception derived from ValidationException. All ValidationExceptions have a Context (ValidationAspects.ValidationContext) member which provides information on the following:
  • Instance (object) - the validated instance.
  • Type (Type) - the validated Type. This could be different to the type of the instance such as when a validator registered to a base type or interface is invoked.
  • Property (PropertyInfo) - the validated Property. This is only set if a Property is being validated.
  • Method (MethodBase) - the validated Method. This is only set if a Property (set method) or Method is being validated.
  • Parameter (ParameterInfo) - the validated Parameter. This is only set if a Property (set method) or Method is being validated.
  • Arguments (object[]) - the Method/Property setter arguments.
This data can be used by an exception's MessageFormat function to provide more detailed exception messages.

Exception Hierarchy

When validation is invoked, all validators registered to the validation target will execute so that all validators have an opportunity to report failed validation and throw an exception. These multiple exceptions are stored within an instance of ValidationAspects.Exceptions.ValidationContextException which is then thrown. This exception stores the Context and its exception message is the same as its first child exception. Child exceptions are accessible via the ValidationContextException.Exceptions property. The result of this is that an exception hierarchy will be caught by client code.

Exception Handling

You should catch a ValidationException. This exception instance will provide the top-level validation context such as the Method invoked which failed validation. If you need to navigate through the exception hierarchy this exception can be cast to a ValidationContextException, however, if all you need from the exception are the validation exception messages, these are accessible from the ValidationException.Messages property. This flattens the exception hierarchy, removing the ValidationContextExceptions, and returns an enumerable of exception message strings.

try
{
  ...
}
catch (ValidationException e)
{
  // report top-level exception message
  // log(e.Message);
  // report all failed validation message
  foreach (string message in e.Messages)
  {
    log(message);
  }
}

Last edited Feb 3, 2009 at 7:37 PM by mikesaunders, version 5

Comments

No comments yet.