A simple, fluent, extensible, and fully customizable library for throwing exceptions for projects using .NET 6+
A simple, fluent, extensible, and fully customizable library for throwing exceptions for projects using .NET 6+
Loving it? Show your support by giving this project a star!
This library is designed to work best with nullable reference types feature enabled.
The Throw() method is the entry method for all non-nullable types:
string name = "hello";
name.Throw().IfLongerThan(10);And ThrowIfNull() for any nullable type:
string? name = "hello";
name.ThrowIfNull();Trying to use Throw() on a nullable type will give a warning
string? name = null;
name.Throw() // warning CS8714: The type 'string?' cannot be used as type parameter 'TValue' in the generic type or method 'ValidatableCreationExtensions.Throw(TValue, ExceptionCustomizations?, string?)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint.
.IfEmpty();After validating that the nullable type isn't null, all the regular non-nullable rules can be used
name.ThrowIfNull()
.IfEmpty()
.IfLongerThan(3);The expression can be implicitly cast to the non-nullable type of the original nullable type
string? name = "Amichai";
string nonNullableName = name.ThrowIfNull()
.IfEmpty()
.IfLongerThan(10);or
int? a = 5;
int b = a.ThrowIfNull();If you have customized the exception, any rule that throws an exception will use the customization. For example:
…At any point, you can change the exception customization, and it will apply for all the rules that follow. For example:
…To go back to the default exception, simply use the Throw() method. For example:
name.Throw("String should not be empty or white space only.")
.IfEmpty() // System.ArgumentException: String should not be empty or white space only. (Parameter 'name')
.IfWhiteSpace() // System.ArgumentException: String should not be empty or white space only. (Parameter 'name')
.Throw()
.IfLongerThan(3) // System.ArgumentException: String should not be longer than 3 characters. (Parameter 'name')
.IfShorterThan(10); // System.ArgumentException: String should not be shorter than 10 characters. (Parameter 'name')Throw()Each rule has a default behavior. If you don't customize the exception, the default behavior will be used.
Use the Throw() or ThrowIfNull() method to throw the default exception
…Throw("My custom message")Pass a custom exception message to the Throw() or ThrowIfNull() method
…Throw(() => new MyException())Pass a custom exception thrower to the Throw() or ThrowIfNull() method
…Throw(paramName => new MyException($"Param: {paramName}")Pass a custom exception thrower to the Throw() or ThrowIfNull() method, that takes the parameter name as a parameter
This comes in handy in scenarios like this:
……value.Throw().IfTrue(); // ArgumentException: Value should not be true (Parameter 'value')
value.Throw().IfFalse(); // ArgumentException: Value should be true (Parameter 'value')
// Any method which returns bool can inline it's exception throwing logic.
Enum.TryParse("Unexpected value", out EmployeeType value)
.Throw()
.IfFalse(); // System.ArgumentException: Value should be true. (Parameter 'Enum.TryParse("Unexpected value", out EmployeeType value)')bool?, int?, double?, DateTime? etc.)bool? value = null;
value.ThrowIfNull(); // ArgumentNullException: Value cannot be null. (Parameter 'value')
// After validating `ThrowIfNull`, any of the regular value type extensions can be used.
value.ThrowIfNull() // ArgumentNullException: Value cannot be null. (Parameter 'value')
.IfTrue(); // ArgumentException: Value should not be true (Parameter 'value')
// The returned value from `ThrowIfNull` can be implicitly cast to the original non-nullable type.
bool nonNullableValue = value.ThrowIfNull(); // ArgumentNullException: Value cannot be null. (Parameter 'value')
…IEnumerable, IEnumerable, ICollection, ICollection, IList, etc.)Important note: if the collection is a non-evaluated expression, the expression will be evaluated.
……employeeType.Throw().IfOutOfRange(); // System.ArgumentOutOfRangeException: Value should be defined in enum. (Parameter 'employeeType')
employeeType.Throw().IfEquals(EmployeeType.FullTime); // System.ArgumentException: Value should not be equal to FullTime. (Parameter 'employeeType')dateTime.Throw().IfDefault(); // System.ArgumentException: Value should not be default. (Parameter 'dateTime')
dateTime.Throw().IfNotDefault(); // System.ArgumentException: Value should be default. (Parameter 'dateTime')
number.Throw().IfEquals(5); // System.ArgumentException: Value should not be not be equal to 5. (Parameter 'number')
number.Throw().IfNotEquals(3); // System.ArgumentException: Value should be equal to 3. (Parameter 'number')…int, double, decimal, long, float, short, DateTime, DateOnly, TimeOnly etc.)…myObject.Throw().IfType(); // System.ArgumentException: Parameter should not be of type 'String'. (Parameter 'myObject').
myObject.Throw().IfNotType(); // System.ArgumentException: Parameter should be of type 'String'. (Parameter 'myObject').………person.Throw().IfOutOfRange(p => p.EmployeeType); // System.ArgumentOutOfRangeException: Value should be defined in enum. (Parameter 'person: p => p.EmployeeType')
person.Throw().IfEquals(p => p.EmployeeType, EmployeeType.FullTime); // System.ArgumentException: Value should not be equal to FullTime. (Parameter 'person: p => p.EmployeeType')………You can easily extend the library by adding your own rules.
Here is a simple example:
"foo".Throw().IfFoo(); // System.ArgumentException: String shouldn't equal 'foo' (Parameter '"foo"')namespace Throw
{
public static class ValidatableExtensions
{
public static ref readonly Validatable IfFoo(this in Validatable validatable)
{
if (string.Equals(validatable.Value, "foo", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("String shouldn't equal 'foo'", validatable.ParamName);
}
return ref validatable;
}
}
}Another example:
user.Throw().IfUsesFacebookOnChrome();namespace Throw
{
public static class ValidatableExtensions
{
public static ref readonly Validatable IfUsesFacebookOnChrome(this in Validatable validatable)
{
if (validatable.Value.FavoriteBrowser == Browser.Chrome && validatable.Value.FavoriteWebsite == new Uri("https://facebook.com"))
{
throw new UserException("User shouldn't use Facebook on Chrome!");
}
return ref validatable;
}
}
}If you want to use the exception customizations in your extension. You can use the ExceptionThrower class which knows how to create the appropriate exception based on the customizations. For example:
namespace Throw
{
public static class ValidatableExtensions
{
public static ref readonly Validatable IfUsesFacebookOnChrome(this in Validatable validatable)
{
if (validatable.Value.FavoriteBrowser == Browser.Chrome && validatable.Value.FavoriteWebsite == new Uri("https://facebook.com"))
{
ExceptionThrower.Throw(validatable.ParamName, validatable.ExceptionCustomizations, "User shouldn't be using Facebook on Chrome.");
}
return ref validatable;
}
}
}This will behave as following:
user.Throw()
.IfUsesFacebookOnChrome(); // System.ArgumentException: User shouldn't be using Facebook on Chrome. (Parameter 'user')user.Throw("A different message.")
.IfUsesFacebookOnChrome(); // System.ArgumentException: A different message. (Parameter 'user')user.Throw(() => new Exception("A different exception."))
.IfUsesFacebookOnChrome(); // System.Exception: A different exception.user.Throw(paramName => new Exception($"A different exception. Param name: '{paramName}'"))
.IfUsesFacebookOnChrome(); // System.Exception: A different exception. Param name: 'user'Have a Throw() rule that you want to exclude from your release build?
Simply add OnlyInDebug() to the rule and it will be excluded from non-debug builds.
"foo".Throw().IfEquals("foo").OnlyInDebug();dotnet run -c Debug # will throwdotnet run -c Release # won't throwFeel free to open an issue with any idea, bug, or feature request.
We are trying to be the fastest validation library, so if you have suggestions on improving the runtime speed, share them with us.
This project is licensed under the terms of the [MIT](https://gith
No open issues yet, or sync has not completed.