Skip to content

Validators and Exceptions

Casey edited this page Apr 6, 2025 · 4 revisions

EntityAxis includes sensible, opinionated defaults for validation and error handling using FluentValidation and custom exceptions to help you enforce consistency and improve developer experience.


✅ Validators

EntityAxis includes generic validators that help enforce consistency across CRUD and query operations.

Built-In Validators

  • CreateEntityValidator<TModel, TEntity, TKey>
  • UpdateEntityValidator<TModel, TEntity, TKey>
  • DeleteEntityValidator<TEntity, TKey>
  • GetEntityByIdValidator<TEntity, TKey>
  • GetPagedEntitiesValidator<TEntity, TKey>

These validators ensure:

  • IDs are not empty or default when required.
  • Pagination parameters are valid (e.g., positive page number and size).
  • Optional model-level validation if a matching IValidator<TModel> is registered.

💡 If no model-level validator is found, EntityAxis will continue without throwing, allowing optional validation.

Example FluentValidation Registration

// Registers custom FluentValidation validators
services.AddValidatorsFromAssemblyContaining(typeof(ProductCreateModelValidator));

✅ Enabling Validation with MediatR

EntityAxis validators work seamlessly with MediatR's pipeline behavior model, but you must explicitly enable it in your application.

If you're using MediatR and want to automatically run validators before executing handlers, you can add a pipeline behavior like this:

services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>));

Note: RequestValidationBehavior<,> is not part of the core EntityAxis libraries. You can find a sample implementation in the sample application or define your own using FluentValidation.


❌ Exceptions

EntityAxis provides a custom EntityNotFoundException to replace vague ApplicationException usage when an entity cannot be located.

This helps distinguish missing-entity conditions in a consistent and catchable way.

Usage in Handlers

if (entity == null)
    throw new EntityNotFoundException(typeof(TEntity), id);

💡 All EntityAxis handlers use this exception by default when an entity is not found.


📚 See Also

Clone this wiki locally