Tooark.Exceptions 4.7.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Tooark.Exceptions --version 4.7.0
                    
NuGet\Install-Package Tooark.Exceptions -Version 4.7.0
                    
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="4.7.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tooark.Exceptions" Version="4.7.0" />
                    
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 4.7.0
                    
#r "nuget: Tooark.Exceptions, 4.7.0"
                    
#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@4.7.0
                    
#: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=4.7.0
                    
Install as a Cake Addin
#tool nuget:?package=Tooark.Exceptions&version=4.7.0
                    
Install as a Cake Tool

Tooark.Exceptions

Library that provides standardized exceptions for .NET projects, mapped to HTTP status codes and supporting several ways to build error messages.

🌍 Languages: πŸ‡ΊπŸ‡Έ English (this file) Β· πŸ‡§πŸ‡· PortuguΓͺs


πŸ“‘ Contents


πŸ“– Overview

Every specific exception of the package inherits from TooarkException, which in turn inherits from Exception. The base class is abstract and its constructors are protected β€” it is not instantiated directly, but extended, either by the package's exceptions or by your application's.

The base class concentrates:

  • error messages (GetErrorMessages());
  • equivalent notifications (GetNotifications());
  • the HTTP status code contract (GetStatusCode()).

Two guarantees hold for every constructor:

  • The collections are read-only. GetErrorMessages() and GetNotifications() always return the same read-only instance, so no external code can empty or alter the error the exception carries β€” which would make a failure vanish in the middle of its handling.
  • The collections are never empty. Null, empty or message-less input records a known key instead of producing an exception that claims to be an error but carries none. The two readings go together: the same position describes the same error in both.

πŸ”§ Installation

dotnet add package Tooark.Exceptions

The package has no configuration and no container registration: the exceptions are thrown and caught directly.


✨ Supported Features

The exception classes support the following constructors:

Constructor Usage
ExceptionType(string message) Single message
ExceptionType(string message, Exception innerException) Single message preserving the root cause
ExceptionType(IList<string> messages) Several messages, for validation with more than one failure
ExceptionType(Notification notification) Reuses notifications already aggregated in the validation layer
ExceptionType(string messageFormat, params object[] args) Dynamic message with {0}, {1}, etc. placeholders

Overload resolution: new NotFoundException("Failure: {0}", exceptionObject) binds to the inner exception constructor, not the formatting one, because Exception is the more specific parameter. To format using an exception as argument, convert it first (for instance ex.Message).

When formatting, a format incompatible with the parameters does not throw: the message is kept as received. The exception exists to report the original error, and failing in its own presentation would trade the real error for a FormatException. Messages with literal braces, such as JSON, fall into this case.


πŸ’¬ Error Messages

The static class ExceptionErrorMessages gathers the messages generated by the package itself. They are translation keys, not final texts.

Constant Value When it occurs
MessageIsNullOrEmpty Exceptions.MessageNullEmpty Null, empty or whitespace-only message
ErrorsIsNullOrEmpty Exceptions.ErrorsNullOrEmpty Null message list or notification, or one without any message

Null handling:

Situation Behavior
null as a single message Records Exceptions.MessageNullEmpty
null or empty list in IList<string> Records Exceptions.ErrorsNullOrEmpty
null or notification without items Records Exceptions.ErrorsNullOrEmpty
Null item inside the list Becomes Exceptions.MessageNullEmpty in both collections

🚨 Available Exceptions

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

The parenthesis shows the System.Net.HttpStatusCode member. For 413 .NET keeps the old name RequestEntityTooLarge, although RFC 7231 calls the status Payload Too Large.


πŸ“ Usage Examples

1) Simple message

throw new BadRequestException("Invalid payload.");

2) Multiple messages

throw new BadRequestException([
  "Name is required.",
  "Invalid email."
]);

3) Formatted message

var userId = 42;
throw new NotFoundException("User with ID {0} not found.", userId);

4) From a Notification

Creating notifications is protected, so the notifying object is the one that notifies:

using Tooark.Notifications;

public sealed class DomainNotification : Notification
{
  public void NotifyRequired(string field) =>
    AddNotification($"{field} is required.", field, "T.DOM1");
}

var notification = new DomainNotification();
notification.NotifyRequired("Document");
notification.NotifyRequired("Phone");

throw new BadRequestException(notification);

The notification items are preserved as they are, keeping the key and the code of each one.

5) Preserving the root cause

try
{
  await _httpClient.GetAsync(url, cancellationToken);
}
catch (HttpRequestException ex)
{
  // The original exception stays reachable in InnerException, for diagnostics
  throw new BadGatewayException("Payment service unavailable.", ex);
}

6) Standardized handling

using Tooark.Exceptions;

try
{
  throw new ServiceUnavailableException("External service unavailable.");
}
catch (TooarkException ex)
{
  var statusCode = ex.GetStatusCode();
  var errors = ex.GetErrorMessages();
  var notifications = ex.GetNotifications();

  Console.WriteLine($"Status: {(int)statusCode} - {statusCode}");
  Console.WriteLine($"First error: {errors[0]}");
  Console.WriteLine($"Notification count: {notifications.Count}");
}

errors[0] is safe: the collections are never empty.

7) State conflict (409)

throw new ConflictException("A user with this email already exists.");

8) Payload too large (413)

throw new PayloadTooLargeException(
  "File exceeds the allowed limit of {0} MB.",
  10
);

9) Unsupported media type (415)

throw new UnsupportedMediaTypeException("Content-Type 'text/plain' is not supported.");

10) Unprocessable entity (422)

throw new UnprocessableEntityException([
  "CPF invalid for the business rule.",
  "Birth date incompatible with the registration."
]);

11) Too many requests (429)

throw new TooManyRequestsException("Request limit exceeded. Try again in a few seconds.");

12) Creating your own exception

The hierarchy is open: inherit from TooarkException and provide the HTTP status code. Every base constructor becomes available, with the same read-only and never-empty collection guarantees.

using System.Net;
using Tooark.Exceptions;
using Tooark.Notifications;

public class PaymentRequiredException : TooarkException
{
  public PaymentRequiredException(string message) : base(message) { }

  public PaymentRequiredException(string message, Exception innerException)
    : base(message, innerException) { }

  public PaymentRequiredException(IList<string> messages) : base(messages) { }

  public PaymentRequiredException(Notification notification) : base(notification) { }

  public PaymentRequiredException(string messageFormat, params object[] args)
    : base(messageFormat, args) { }

  public override HttpStatusCode GetStatusCode() => HttpStatusCode.PaymentRequired;
}

The catch (TooarkException ex) of the standardized handling now catches it together with the others.


πŸ“‹ Dependencies

Package Version Usage
Tooark.Notifications 4.x Notification and NotificationItem

The package does not depend on ASP.NET Core: the HTTP status code is exposed as System.Net.HttpStatusCode, from the runtime itself, and translating it into the response is up to the application.


🀝 Contributing

Contributions are welcome! Start with CONTRIBUTING.md β€” it covers the development workflow, the coding and commit conventions and the pull request checklist. Bugs and feature requests go through the issue templates of the Tooark repository.

By participating you agree to the Code of Conduct.


πŸ†˜ Help & Security

  • ❓ Questions, bugs, feature ideas β€” see SUPPORT.md for the right channel
  • πŸ”’ Security vulnerabilities β€” do not open a public issue; follow SECURITY.md

πŸ’– Support

If Tooark helps your projects, consider supporting its development:

Every contribution helps keep the project maintained and improving. Thank you! πŸ™


πŸ“„ License

This project is licensed under the BSD 3-Clause License.

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

NuGet packages (15)

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

Package Downloads
Tooark.Utils

General utility package for .NET applications.

Tooark.Enums

Package for creating validated enumerators for .NET applications.

Tooark.ValueObjects

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

Tooark.Entities

Package for managing base entities in .NET applications.

Tooark.Attributes

Package for creating attribute validators for .NET applications.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.7.1 0 10/17/2026
4.7.0 568 9/30/2026
4.6.0 328 9/29/2026
4.5.0 309 9/29/2026
4.4.0 305 9/28/2026
4.3.0 312 9/26/2026
4.2.1 303 9/25/2026
4.2.0 330 9/20/2026
4.1.0 303 9/18/2026
4.0.1 367 8/25/2026
4.0.0 372 8/25/2026
3.3.6 219 9/18/2026
3.3.5 254 8/25/2026
3.3.4 431 8/12/2026
3.3.3 529 7/27/2026
3.3.2 531 6/11/2026
3.3.1 316 6/6/2026
2.3.5 178 9/18/2026
2.3.4 207 8/25/2026
2.3.3 235 7/27/2026
Loading failed