Tooark.Exceptions 3.2.2

dotnet add package Tooark.Exceptions --version 3.2.2
                    
NuGet\Install-Package Tooark.Exceptions -Version 3.2.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tooark.Exceptions" Version="3.2.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tooark.Exceptions" Version="3.2.2" />
                    
Directory.Packages.props
<PackageReference Include="Tooark.Exceptions" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tooark.Exceptions --version 3.2.2
                    
#r "nuget: Tooark.Exceptions, 3.2.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tooark.Exceptions@3.2.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tooark.Exceptions&version=3.2.2
                    
Install as a Cake Addin
#tool nuget:?package=Tooark.Exceptions&version=3.2.2
                    
Install as a Cake Tool

Tooark.Exceptions

Biblioteca que fornece exceções padronizadas para projetos .NET, com mapeamento para status HTTP e suporte a múltiplas formas de construção de mensagens de erro.

Conteúdo

Visão Geral

Todas as exceções específicas do pacote herdam de TooarkException, que por sua vez herda de Exception.

A classe base concentra:

  • armazenamento de mensagens de erro (GetErrorMessages());
  • armazenamento de notificações (GetNotifications());
  • contrato para código HTTP (GetStatusCode()).

Recursos Suportados

As classes de exceção suportam os seguintes construtores:

  • ExceptionType(string message)
  • ExceptionType(IList<string> messages)
  • ExceptionType(Notification notification)
  • ExceptionType(string messageFormat, params object[] args)

Novos recursos documentados

  • Mensagem formatada com placeholders: permite criar mensagens dinâmicas com string.Format.
  • Integração com Notification: reutiliza mensagens/notificações já agregadas na camada de validação.
  • Múltiplas mensagens: suporta lista de erros para cenários de validação com mais de uma falha.

Exceções Disponíveis

Classe Status HTTP
BadRequestException 400 (BadRequest)
GetInfoException 400 (BadRequest)
UnauthorizedException 401 (Unauthorized)
ForbiddenException 403 (Forbidden)
NotFoundException 404 (NotFound)
MethodNotAllowedException 405 (MethodNotAllowed)
ConflictException 409 (Conflict)
PayloadTooLargeException 413 (PayloadTooLarge)
UnsupportedMediaTypeException 415 (UnsupportedMediaType)
UnprocessableEntityException 422 (UnprocessableEntity)
TooManyRequestsException 429 (TooManyRequests)
InternalServerErrorException 500 (InternalServerError)
BadGatewayException 502 (BadGateway)
ServiceUnavailableException 503 (ServiceUnavailable)
GatewayTimeoutException 504 (GatewayTimeout)

Exemplos de Uso

1) Mensagem simples

throw new BadRequestException("Payload inválido.");

2) Múltiplas mensagens

throw new BadRequestException([
  "Nome é obrigatório.",
  "E-mail inválido."
]);

3) Mensagem formatada (novo)

var userId = 42;
throw new NotFoundException("Usuário com ID {0} não encontrado.", userId);

4) A partir de Notification (novo)

using Tooark.Notifications;

public sealed class DomainNotification : Notification { }

var notification = new DomainNotification();
notification.AddNotification("Documento é obrigatório.", "Document");
notification.AddNotification("Telefone inválido.", "Phone");

throw new BadRequestException(notification);

5) Tratamento padronizado

using Tooark.Exceptions;

try
{
  throw new ServiceUnavailableException("Serviço externo indisponível.");
}
catch (TooarkException ex)
{
  var statusCode = ex.GetStatusCode();
  var errors = ex.GetErrorMessages();
  var notifications = ex.GetNotifications();

  Console.WriteLine($"Status: {(int)statusCode} - {statusCode}");
  Console.WriteLine($"Primeiro erro: {errors.FirstOrDefault()}");
  Console.WriteLine($"Total de notificações: {notifications.Count}");
}

6) Conflito de estado (409)

throw new ConflictException("Já existe um usuário com este e-mail.");

7) Payload muito grande (413)

throw new PayloadTooLargeException(
  "Arquivo excede o limite permitido de {0} MB.",
  10
);

8) Tipo de mídia não suportado (415)

throw new UnsupportedMediaTypeException("Content-Type 'text/plain' não é suportado.");

9) Entidade não processável (422)

throw new UnprocessableEntityException([
  "CPF inválido para a regra de negócio.",
  "Data de nascimento incompatível com o cadastro."
]);

10) Muitas requisições (429)

throw new TooManyRequestsException("Limite de requisições excedido. Tente novamente em alguns segundos.");

Dependências

Contribuição

Contribuições são bem-vindas! Sinta-se à vontade para abrir issues e pull requests no repositório Tooark.

Licença

Este projeto está licenciado sob a licença BSD 3-Clause. Veja LICENSE para mais detalhes.

Product 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 was computed.  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 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (5)

Showing the top 5 NuGet packages that depend on Tooark.Exceptions:

Package Downloads
Tooark.Utils

General utility package for .NET applications.

Tooark.Entities

Package for managing base entities in .NET applications.

Tooark

Package with all Tooark resources for .NET applications.

Tooark.Securities

Package for managing predefined and validated Security Objects for .NET applications.

Tooark.Observability

Package providing OpenTelemetry-based observability (traces, metrics, logs) with sensible defaults and easy configuration via appsettings for .NET applications.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.2.2 57 3/23/2026
3.2.1 68 3/23/2026
3.2.0 286 1/21/2026
3.1.0 216 1/10/2026
3.0.0 233 1/9/2026
2.3.1 47 3/23/2026
2.3.0 207 1/21/2026
2.2.1 200 1/6/2026
2.2.0 195 1/6/2026
2.1.9 317 10/29/2025
2.1.8 1,030 6/26/2025
2.1.7 402 6/17/2025
2.1.6 539 6/15/2025
2.1.5 282 6/14/2025
2.1.4 281 6/3/2025
2.1.3.3 283 6/3/2025
2.1.3.2 277 6/3/2025
2.1.3 291 6/3/2025
2.1.2 446 5/17/2025
2.1.1 224 5/3/2025
Loading failed