Its.Validation icon indicating copy to clipboard operation
Its.Validation copied to clipboard

Validate no exception thrown; but if thrown use Exception message in WithErrorMessage

Open SurajGupta opened this issue 8 years ago • 1 comments

I'd like to validate that an object can be constructed without throwing an exception, If an exception is thrown, I'd like to report the Exception message.

I'm trying an approach like this - but not sure if it can be made to work? Is there a better way to do this?

Validate.That<MyType>(
    t =>
    {
        new MyType(...);
        return true;
    })
.Handle<ArgumentException, MyType>()
.WithErrorMessage( <I'd like to use ArgumentException.Message, but also happy to just have the error message be Exception.ToString()> )

SurajGupta avatar Dec 06 '17 22:12 SurajGupta

Rather than use exceptions for control flow, I like to extract the validation logic into something that returns an answer directly, e.g.:

public class MyType
{
  public MyType(string foo, int bar)
  {
    var report = CanBeInitializedWith((foo, bar));
    if (report.HasFailures) throw ...;
  }
  
  public static ValidationReport CanBeInitializedWith((string foo, int bar) t) => 
        Validate.That<(string foo, int bar>((args) => /* ... */).Execute(t);
}

This way, callers can pre-validate using the same logic that the constructor will use. This approach might be useful when user input is passed to a constructor and you want to give nicer error messages and reduce exception noise.

jonsequitur avatar Dec 08 '17 00:12 jonsequitur