Pitasoft.Error
5.3.6
See the version list below for details.
dotnet add package Pitasoft.Error --version 5.3.6
NuGet\Install-Package Pitasoft.Error -Version 5.3.6
<PackageReference Include="Pitasoft.Error" Version="5.3.6" />
<PackageVersion Include="Pitasoft.Error" Version="5.3.6" />
<PackageReference Include="Pitasoft.Error" />
paket add Pitasoft.Error --version 5.3.6
#r "nuget: Pitasoft.Error, 5.3.6"
#:package Pitasoft.Error@5.3.6
#addin nuget:?package=Pitasoft.Error&version=5.3.6
#tool nuget:?package=Pitasoft.Error&version=5.3.6
Pitasoft.Error
Pitasoft.Error is a class library designed to facilitate the handling and management of error collections in .NET applications. It allows grouping errors by property, handling change notifications, and serializing/deserializing error collections to/from JSON.
English
Key Features
- ErrorCollection: A robust collection for storing errors associated with property names.
- Factory Properties: Access
ErrorCollection.Emptyfor a fresh, empty collection instance. - IErrorCollectionContainer: A standard interface for objects (like ViewModels) that expose an
ErrorCollection. - High Performance: Optimized for low memory allocation and fast execution, especially in filtering and mass clearing operations.
- Advanced Filtering: Flexible error retrieval using
IntersectorExceptoperations withJointActionErrors. - INotifyDataErrorInfo Support: Fully implements
INotifyDataErrorInfofor seamless integration with WPF, Avalonia UI, MAUI, and other data-binding frameworks. - UI Integration Samples: Includes sample projects for WPF and Avalonia UI showing real-time validation patterns.
- Notifications: Support for events when the error collection changes.
- Total Error Counting: The
Countproperty returns the total number of individual error messages across all properties. - JSON Serialization: Built-in extensions to convert error collections to JSON and vice versa.
- Lambda-based Extensions: Type-safe property selection via
Expression<Func<T, object?>>extensions (no magic strings). - Multi-target Support: Compatible with .NET 8.0, .NET 9.0, and .NET 10.0.
- Fluent API: Chainable methods for fast and readable error collection setup.
- Exception Error Detection: Automatic error message extraction from complex exception hierarchies.
Installation
You can install this package via NuGet:
dotnet add package Pitasoft.Error
Basic Usage
Quick Error Access
// Get the first error message across all properties (useful for summary UI)
string? firstError = errors.FirstOrDefault();
// Check for errors on a single property (fast O(1) check)
bool hasNameErrors = errors.AnyError("Name");
Creating an Error Collection and Adding/Clearing Errors
using Pitasoft.Error;
// Create using constructor or factory property
var errors = ErrorCollection.Empty;
// Fluent API: chain additions seamlessly
errors.Add("Name", "The name is required.")
.Add("Email", "The email format is invalid.");
// Count returns the total number of individual error messages (2 in this case)
int totalErrors = errors.Count;
// Support for multiple errors at once (params string[])
errors.Add("Status", "Invalid value", "Out of range");
if (errors.AnyError())
{
// Handle errors globally
}
// Clear errors for a specific property
errors.Clear("Name");
// Clear all errors
errors.ClearAll();
Note: The
RemoveandRemoveAllmethods are now deprecated in favor ofClearandClearAllto maintain naming consistency with standard .NET collections.
Methods Without Notifications
If you need to add errors without triggering the ErrorsChanged event:
errors.AddWithoutNotification("SilentProperty", "This error won't trigger an event.");
UI Frameworks Integration (MVVM)
ErrorCollection is designed to be easily integrated into ViewModels. You can implement IErrorCollectionContainer to provide a standard way of exposing errors:
public class MyViewModel : INotifyDataErrorInfo, IErrorCollectionContainer
{
public ErrorCollection Errors { get; set; } = new();
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged
{
add => Errors.ErrorsChanged += value;
remove => Errors.ErrorsChanged -= value;
}
public System.Collections.IEnumerable GetErrors(string? propertyName) =>
((INotifyDataErrorInfo)Errors).GetErrors(propertyName);
public bool HasErrors => Errors.HasErrors;
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
ValidateName();
}
}
private void ValidateName()
{
Errors.Clear(nameof(Name));
if (string.IsNullOrWhiteSpace(Name))
Errors.Add(nameof(Name), "Name is required");
}
}
Check the Pitasoft.Error.WpfSample and Pitasoft.Error.AvaloniaSample projects for complete implementations.
Advanced Filtering
You can filter errors using JointActionErrors to include or exclude specific properties:
// Get errors only for specific properties
var relevantErrors = errors.GetErrors(JointActionErrors.Intersect, "Username", "Password");
// Get errors for all properties EXCEPT the ones specified
var otherErrors = errors.GetErrors(JointActionErrors.Except, "IsAcceptedTerms");
// Check if any error exists for specific properties
bool hasCriticalErrors = errors.AnyError(JointActionErrors.Intersect, "System", "Database");
Using Static Creation Methods
var errors = ErrorCollection.Create("General", "An unexpected error has occurred.");
JSON Serialization
using Pitasoft.Error.Extensions;
string json = errors.ToJson();
Deserialization from JSON
string json = "{\"name\":[\"Error 1\"]}";
var errors = json.ToErrorCollection();
Lambda-friendly Extensions
These helpers live in the Pitasoft.Error.Extensions namespace.
using Pitasoft.Error;
using Pitasoft.Error.Extensions;
var errors = new ErrorCollection();
// Add errors without magic strings
errors.Add<MyViewModel>(vm => vm.Name, "Name is required");
errors.Add<MyViewModel>(vm => vm.Email, "Invalid format", "Domain not allowed");
// Query errors
bool hasEmailErrors = errors.AnyError<MyViewModel>(vm => vm.Email);
// Joint checks (Intersect/Except)
bool anyUserFieldHasErrors = errors.AnyError<MyViewModel>(JointActionErrors.Intersect,
vm => vm.Name, vm => vm.Email);
// Clear by property expression
errors.Clear<MyViewModel>(vm => vm.Email);
errors.Clear<MyViewModel>(vm => vm.Name, vm => vm.Email);
errors.Clear<MyViewModel>(notification: false, vm => vm.Name);
// Factory methods
var created = ErrorCollectionExtensions.Create<MyViewModel>(vm => vm.Name, "Required");
Note: Lambdas are implemented as extension methods to keep
ErrorCollectionlean. Performance is comparable to string-based overloads for typical MVVM usage.
Event Notifications
You can subscribe to changes in the error collection:
var errors = new ErrorCollection();
errors.ErrorsChanged += (sender, e) =>
{
Console.WriteLine($"Property '{e.PropertyName}' was updated.");
};
errors.Add("Username", "Already exists.");
Exception Handling
Easily convert exceptions into error collections:
try
{
// Some code that throws
}
catch (Exception ex)
{
// Using static creation method
var errors = ErrorCollection.Create(ex, deep: true);
// OR using extension method
var errorsExt = ex.ToErrorCollection(deep: true);
// OR using implicit operator
ErrorCollection errorsImplicit = ex;
// All inner exceptions are now captured in the collection
}
License
This project is licensed under the terms specified in the LICENSE.txt file.
Benchmarks
The project is highly optimized for performance. Below is a comparison of typical operations between .NET 8.0 and .NET 10.0:
| Method | Mean Time (.NET 8.0) | Mean Time (.NET 10.0) | Allocated Memory |
|---|---|---|---|
AnyError |
< 1 ns | < 1 ns | 0 B |
AnyErrorProperty |
~3.5 ns | ~2.7 ns | 0 B |
GetProperties |
~23.0 ns | ~14.4 ns | 96 B |
AddError |
~36.1 ns | ~27.9 ns | 376 B |
GetErrors |
~120.0 ns | ~99.8 ns | 376 B |
The new version of .NET 10.0 shows a significant improvement in both execution time and memory allocation efficiency for several operations.
Author
Sebastián Martínez Pérez - Pitasoft, S.L.
Español
Pitasoft.Error es una biblioteca de clases diseñada para facilitar el manejo y la gestión de colecciones de errores en aplicaciones .NET. Permite agrupar errores por propiedad, manejar notificaciones de cambios y serializar/deserializar colecciones de errores a JSON.
Características principales
- ErrorCollection: Una colección robusta para almacenar errores asociados a nombres de propiedades.
- Propiedades de Factoría: Accede a
ErrorCollection.Emptypara obtener una nueva instancia vacía de la colección. - IErrorCollectionContainer: Interfaz estándar para objetos (como ViewModels) que exponen una
ErrorCollection. - Alto Rendimiento: Optimizada para minimizar las asignaciones de memoria y maximizar la velocidad, especialmente en operaciones de filtrado y limpieza masiva.
- Filtrado Avanzado: Recuperación flexible de errores mediante operaciones
IntersectoExceptconJointActionErrors. - Soporte INotifyDataErrorInfo: Implementa completamente
INotifyDataErrorInfopara una integración fluida con WPF, Avalonia UI, MAUI y otros marcos de trabajo con enlace de datos. - Ejemplos de Integración UI: Incluye proyectos de ejemplo para WPF y Avalonia UI que muestran patrones de validación en tiempo real.
- Notificaciones: Soporte para eventos cuando la colección de errores cambia.
- Conteo Total de Errores: La propiedad
Countdevuelve el número total de mensajes de error individuales en todas las propiedades. - Serialización JSON: Extensiones integradas para convertir colecciones de errores a JSON y viceversa.
- Métodos de extensión con expresiones lambda: Selección tipada de propiedades mediante
Expression<Func<T, object?>>(sin cadenas mágicas). - Soporte Multi-target: Compatible con .NET 8.0, .NET 9.0 y .NET 10.0.
- Fluent API: Métodos encadenables para una configuración rápida y legible de las colecciones de errores.
- Detección de Errores de Excepción: Extracción automática de mensajes de error de jerarquías de excepciones complejas.
Instalación
Puedes instalar este paquete a través de NuGet:
dotnet add package Pitasoft.Error
Uso básico
Acceso rápido a errores
// Obtener el primer mensaje de error de todas las propiedades (útil para resúmenes en la UI)
string? primerError = errors.FirstOrDefault();
// Comprobar errores en una propiedad específica (comprobación rápida O(1))
bool tieneErroresNombre = errors.AnyError("Nombre");
Crear una colección de errores, añadir y limpiar errores
using Pitasoft.Error;
// Crear mediante constructor o propiedad de factoría
var errors = ErrorCollection.Empty;
// Fluent API: encadenar adiciones de forma fluida
errors.Add("Nombre", "El nombre es obligatorio.")
.Add("Email", "El formato del email no es válido.");
// Count devuelve el número total de mensajes de error individuales (2 en este caso)
int totalErrores = errors.Count;
// Soporte para múltiples errores a la vez (params string[])
errors.Add("Estado", "Valor inválido", "Fuera de rango");
if (errors.AnyError())
{
// Manejar errores de forma global
}
// Limpiar errores de una propiedad específica
errors.Clear("Nombre");
// Limpiar todos los errores
errors.ClearAll();
Nota: Los métodos
RemoveyRemoveAllhan sido marcados como obsoletos en favor deClearyClearAllpara mantener la consistencia con las colecciones estándar de .NET.
Métodos sin notificaciones
Si necesitas añadir errores sin disparar el evento ErrorsChanged:
errors.AddWithoutNotification("PropiedadSilenciosa", "Este error no disparará un evento.");
Integración con Frameworks de UI (MVVM)
ErrorCollection está diseñado para integrarse fácilmente en ViewModels. Puedes implementar IErrorCollectionContainer para proporcionar una forma estándar de exponer errores:
public class MiViewModel : INotifyDataErrorInfo, IErrorCollectionContainer
{
public ErrorCollection Errors { get; set; } = new();
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged
{
add => Errors.ErrorsChanged += value;
remove => Errors.ErrorsChanged -= value;
}
public System.Collections.IEnumerable GetErrors(string? propertyName) =>
((INotifyDataErrorInfo)Errors).GetErrors(propertyName);
public bool HasErrors => Errors.HasErrors;
private string _nombre;
public string Nombre
{
get => _nombre;
set
{
_nombre = value;
ValidarNombre();
}
}
private void ValidarNombre()
{
Errors.Clear(nameof(Nombre));
if (string.IsNullOrWhiteSpace(Nombre))
Errors.Add(nameof(Nombre), "El nombre es obligatorio");
}
}
Consulta los proyectos Pitasoft.Error.WpfSample y Pitasoft.Error.AvaloniaSample para implementaciones completas.
Filtrado Avanzado
Puedes filtrar errores usando JointActionErrors para incluir o excluir propiedades específicas:
// Obtener errores solo para propiedades específicas
var erroresRelevantes = errors.GetErrors(JointActionErrors.Intersect, "Usuario", "Password");
// Obtener errores para todas las propiedades EXCEPTO las especificadas
var otrosErrores = errors.GetErrors(JointActionErrors.Except, "AceptaTerminos");
// Comprobar si existe algún error para propiedades específicas
bool tieneErroresCriticos = errors.AnyError(JointActionErrors.Intersect, "Sistema", "BaseDeDatos");
Uso de métodos estáticos de creación
var errors = ErrorCollection.Create("General", "Ha ocurrido un error inesperado.");
Serialización a JSON
using Pitasoft.Error.Extensions;
string json = errors.ToJson();
Deserialización desde JSON
string json = "{\"nombre\":[\"Error 1\"]}";
var errors = json.ToErrorCollection();
Extensiones con expresiones lambda
Estas utilidades residen en el espacio de nombres Pitasoft.Error.Extensions.
using Pitasoft.Error;
using Pitasoft.Error.Extensions;
var errors = new ErrorCollection();
// Añadir errores sin cadenas mágicas
errors.Add<MiViewModel>(vm => vm.Nombre, "El nombre es obligatorio");
errors.Add<MiViewModel>(vm => vm.Email, "Formato inválido", "Dominio no permitido");
// Consultar errores
bool tieneErroresEmail = errors.AnyError<MiViewModel>(vm => vm.Email);
// Consultas conjuntas (Intersect/Except)
bool algunCampoUsuarioConErrores = errors.AnyError<MiViewModel>(JointActionErrors.Intersect,
vm => vm.Nombre, vm => vm.Email);
// Limpiar por expresión de propiedad
errors.Clear<MiViewModel>(vm => vm.Email);
errors.Clear<MiViewModel>(vm => vm.Nombre, vm => vm.Email);
errors.Clear<MiViewModel>(notification: false, vm => vm.Nombre);
// Factorías
var creado = ErrorCollectionExtensions.Create<MiViewModel>(vm => vm.Nombre, "Requerido");
Nota: Las lambdas están implementadas como métodos de extensión para mantener
ErrorCollectionligera. El rendimiento es comparable a las sobrecargas basadas en cadenas para uso MVVM típico.
Notificaciones de Eventos
Puedes suscribirte a los cambios en la colección de errores:
var errors = new ErrorCollection();
errors.ErrorsChanged += (sender, e) =>
{
Console.WriteLine($"La propiedad '{e.PropertyName}' ha sido actualizada.");
};
errors.Add("Usuario", "Ya existe.");
Manejo de Excepciones
Convierte fácilmente excepciones en colecciones de errores:
try
{
// Código que lanza una excepción
}
catch (Exception ex)
{
// Usando el método de creación estático
var errors = ErrorCollection.Create(ex, deep: true);
// O usando el método de extensión
var errorsExt = ex.ToErrorCollection(deep: true);
// O usando el operador implícito
ErrorCollection errorsImplicit = ex;
// Todas las excepciones internas se capturan ahora en la colección
}
Licencia
Este proyecto está bajo la licencia especificada en el archivo LICENSE.txt.
Benchmarks
El proyecto está altamente optimizado. A continuación se muestra una comparativa de operaciones típicas entre .NET 8.0 y .NET 10.0:
| Método | Tiempo Medio (.NET 8.0) | Tiempo Medio (.NET 10.0) | Memoria Asignada |
|---|---|---|---|
AnyError |
< 1 ns | < 1 ns | 0 B |
AnyErrorProperty |
~3.5 ns | ~2.7 ns | 0 B |
GetProperties |
~23.0 ns | ~14.4 ns | 96 B |
AddError |
~36.1 ns | ~27.9 ns | 376 B |
GetErrors |
~120.0 ns | ~99.8 ns | 376 B |
La nueva versión de .NET 10.0 muestra una mejora significativa tanto en tiempo de ejecución como en eficiencia de asignación de memoria para varias operaciones.
Autor
Sebastián Martínez Pérez
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (5)
Showing the top 5 NuGet packages that depend on Pitasoft.Error:
| Package | Downloads |
|---|---|
|
Pitasoft.Result
.NET library designed to standardize responses from REST services and internal application layers. It provides a robust set of classes to wrap data, status codes, and error collections, facilitating a unified communication contract between APIs, services, and clients. |
|
|
Pitasoft.Validation
A flexible and high-performance C# validation library designed to validate objects using multiple strategies, including Data Annotations, custom rules, and a fluent API. |
|
|
Pitasoft.Web
Librerias basicas de aplicaciones web |
|
|
Pitasoft.AspNetCore
Librerias basicas de aplicaciones web |
|
|
Pitasoft.Blazor.Validation
Blazor components for data validation in forms. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 5.3.14 | 699 | 3/23/2026 |
| 5.3.13 | 136 | 3/23/2026 |
| 5.3.12 | 119 | 3/23/2026 |
| 5.3.11 | 150 | 3/22/2026 |
| 5.3.10 | 123 | 3/22/2026 |
| 5.3.9 | 126 | 3/22/2026 |
| 5.3.8 | 199 | 3/20/2026 |
| 5.3.7 | 244 | 3/13/2026 |
| 5.3.6 | 201 | 3/10/2026 |
| 5.3.5 | 131 | 3/10/2026 |
| 5.3.4 | 127 | 3/10/2026 |
| 5.3.3 | 128 | 3/9/2026 |
| 5.3.2 | 329 | 3/2/2026 |
| 5.3.1 | 264 | 2/24/2026 |
| 5.2.2 | 197 | 2/23/2026 |
| 5.2.1 | 128 | 2/22/2026 |
| 5.1.1 | 136 | 2/17/2026 |
| 5.0.3 | 185 | 2/4/2026 |
| 5.0.2 | 197 | 1/26/2026 |
| 5.0.1 | 140 | 1/26/2026 |