Custom exception from custom validator

Dec 18, 2011 at 10:03 PM

There is an explanation in the docs, of how to add custom exceptions to the library: It requires subclassing the "ConditionValidator<T>", which means that you cannot use "Condition.Requires()", but must use "CustomWhatever.Requires()", which I don't like.

Suppose I'd like to throw a "ArgumentFailureException" when my custom validator fails. So, in my custom validator, may I write:
    throw new ArgumentFailureException("kaboom!");
instead of:

Will I break something in the library?

Dec 19, 2011 at 8:27 AM

That will work. ThrowException is purely there to abstract the exception type that's being thrown.

Something else what you can do is define an extension method over ConditionValidator<T> that returns a new ConditionValidator<T> sub type. This way you can reuse all existing validation methods. You can do something like this:

Condition.Requires(val, "val").ThrowSomethingElse()
    .IsInRange(10, 99);

Dec 19, 2011 at 7:27 PM
Edited Dec 19, 2011 at 7:35 PM

So what you're saying:

* define a new validator "MyValidator<T>" which is a subclass of "ConditionValidator<T>"

* that subclass has a copy constructor which accepts an instance of the parent type as an argument

* "ThrowSomethingElse()" is an extension method on an instance of "ConditionValidator<T>"

* it returns a new instance of "MyValidator<T>"

* and... the subclass can throw custom exceptions


This approach is much more intuitive than that in the docs, I like it. But isn't simply throwing a custom exception from the custom validator simpler (surely I get access to the base class from my custom validator anyway)?

Dec 20, 2011 at 11:51 AM

That sounds like right. Here's an example:

public static ConditionValidator<T> ThrowSomethingElse<T>(
    this ConditionValidator<T> validator)
    return new MyValidator<T>(validator.Value, validator.ArgumentName);

private sealed class MyValidator<T> : ConditionValidator<T>
    protected override void ThrowExceptionCore(string condition,
        string additionalMessage, ConstraintViolationType type)
        throw new ArgumentFailureException(
            condition + ". " + additionalMessage); 
Writing your own Validation method might be simpler, but this prevents you from using all the predefined validation methods that are already in the framework.

Marked as answer by dot_NET_Junkie on 8/14/2014 at 12:34 AM
Dec 21, 2011 at 8:30 AM

Makes sense now, thanks