项目作者: daredever

项目描述 :
WIP: A high-performance validation library with support of C# 8.0 nullable reference types
高级语言: C#
项目地址: git://github.com/daredever/Throw.If.git
创建时间: 2020-06-24T12:40:45Z
项目社区:https://github.com/daredever/Throw.If

开源协议:MIT License

下载


Throw.If

A high-performance validation library with support of C# 8.0 nullable reference types.

Use

  1. using ThrowIf;
  2. Throw.ArgumentNullException()
  3. .If(guid.IsNull(), nameof(guid))
  4. .If(text.IsNull(), nameof(text));
  5. Throw.ArgumentException(name => $"Invalid argument '{name}'")
  6. .If(text.IsEmpty(), nameof(text))
  7. .If(text.Length > 1, nameof(text.Length))
  8. .If(guid.IsEmpty(), nameof(guid));

Default exceptions:

  • ArgumentNullException
  • ArgumentException
  • InvalidOperationException

Default validators:

  • IsNull()
  • IsEmpty()

Default message templates:

  • $”{name} can not be null”
  • $”{name} can not be empty”
  • $”{name} is not valid”

Extend

To use any other exception define factory:

  1. using ThrowIf;
  2. Throw.Exception((name, message) => new CustomException(message), name => $"Wrong parameter '{name}'")
  3. .If(text.IsNull() || text.StartsWith('A'), nameof(text))
  4. .If(text.Length < 100, nameof(text.Length), name => $"{name} is too small");

To reduce the amount of code implement an IConditionGroup interface:

  1. using ThrowIf;
  2. using static ThrowIf.MessageTemplates;
  3. Throw.ArgumentException()
  4. .If(condition: text.IsNull(), name: nameof(text), messageTemplate: CanNotBeNull)
  5. .If(conditionGroup: new TextValidator(), value: text);
  6. public sealed class TextValidator : IConditionGroup<string>
  7. {
  8. public void Verify(in ThrowContext context, string text)
  9. {
  10. context
  11. .If(text.Length < 100, nameof(text.Length), name => $"{name} can not be less than 100")
  12. .If(text.StartsWith('A'), nameof(text), name => $"{name} can not start with char 'A'")
  13. .If(text.EndsWith('B'), nameof(text), name => $"{name} can not end with char 'B'");
  14. }
  15. }

To add new methods extend ThrowContext with extension (impossible to use nullable reference types attributes in some cases):

  1. using ThrowIf;
  2. Throw.ArgumentException()
  3. .If(condition: text.IsNull(), name: nameof(text), messageTemplate: MessageTemplates.CanNotBeNull)
  4. .IfEmpty(value: text, name: nameof(text));
  5. public static class ThrowExtensions
  6. {
  7. public static ref readonly ThrowContext IfEmpty(this in ThrowContext context,
  8. string value, string name)
  9. {
  10. return ref context.If(value.IsEmpty(), name, MessageTemplates.CanNotBeEmpty);
  11. }
  12. }