ToolPack.Exceptions.Web 2.0.0

dotnet add package ToolPack.Exceptions.Web --version 2.0.0                
NuGet\Install-Package ToolPack.Exceptions.Web -Version 2.0.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="ToolPack.Exceptions.Web" Version="2.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add ToolPack.Exceptions.Web --version 2.0.0                
#r "nuget: ToolPack.Exceptions.Web, 2.0.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.
// Install ToolPack.Exceptions.Web as a Cake Addin
#addin nuget:?package=ToolPack.Exceptions.Web&version=2.0.0

// Install ToolPack.Exceptions.Web as a Cake Tool
#tool nuget:?package=ToolPack.Exceptions.Web&version=2.0.0                

ToolPack Exceptions

Solution to operate exceptions in .NET services, both by providing exception/problem models, guard methods and exception handlers for REST and gRPC APIs.

This resorts on two projects: ToolPack.Exceptions.Base and ToolPack.Exceptions.Web.

This aims to be a framework that fully supports the error handling in .NET services. The following main components are exposed:

Other contents:

ToolPack.Exceptions.Base

Exception entities

  • Predefined custom exception entities that may be used anywhere in the code. These are also used by the guards, services and handlers.
  • Namespace: ToolPack.Exceptions.Base.Entities

Entities list:

  • CustomBaseException

    • Custom exception that is parent of all the exceptions listed here
    • When an exception is a CustomBaseException, it is already known that such exception comes from an owned system
  • AlreadyExistsException

    • To occur when an entity is already present in the system
    • Ex.: When a primary key value is already in use
  • ExternalComponentException

    • To occur when an external component in which the system depends failed to operate correctly/answer successfully
    • Exs.: When a partner's API failed to respond; When a third-party package broke its operation; When a message was not received
  • NotFoundException

    • To occur when an entity that was looked for does not exist
    • Ex.: When an entity identified with a given value/key does not exist
  • ValidationFailedException

    • To occur when inputs are not correctly provided to the system
    • Ex.: When a consumer uses an API with wrong parameters

Exception guards

  • Guard methods that validate typical conditions and throw related exceptions when these are not met.
  • Namespace: ToolPack.Exceptions.Base.Guard

ToolPack.Exceptions.Web

Dependency Injection extensions

  • Extension methods that inject the ToolPack Exception services/dependencies to the given application.
  • Namespace: ToolPack.Exceptions.Web.Extensions

Methods list:

  • AddToolPackExceptions(this IServiceCollection services)

    • Adds the ToolPack Exceptions framework services that treat exceptions. It does not include gRPC interceptors nor ASP.NET middleware (for such, see the other extension methods).
  • AddToolPackExceptionsGrpc(this IServiceCollection services)

    • Adds all the ToolPack Exceptions framework required for gRPC services, to handle exceptions globally in gRPC calls. If handling exceptions in REST endpoints is required, proper middleware must be used (see extension UseToolPackExceptionsMiddleware).
  • AddToolPackExceptionsGrpcInterceptor(this IServiceCollection services)

    • Adds the ToolPack Exceptions interceptor services, to handle exceptions globally in gRPC calls. It must not be used in REST APIs; in such cases, exceptions must be handled with proper middleware (see extension UseToolPackExceptionsMiddleware). It does not add the ToolPack Exceptions framework services that treat exceptions; for such, use AddToolPackExceptionsGrpc or AddToolPackExceptions.
  • UseToolPackExceptionsMiddleware(this IApplicationBuilder appBuilder)

    • Uses the ToolPack Exceptions middleware, to handle exceptions globally in the request pipeline. It must not be used in gRPC APIs; in such cases, exceptions must be handled with interceptors (see extensions AddToolPackExceptionsGrpc and AddToolPackExceptionsGrpcInterceptor). It does not add the ToolPack Exceptions framework services that treat exceptions, so the extension AddToolPackExceptions must also be used.

Error models

  • Custom models that relate with errors information and allow the correct handling of exceptions.
  • Namespace: ToolPack.Exceptions.Web.Models

Models list:

  • ProblemDetails

  • WebErrorStatus

    • Placeholder to relate an HTTP status code (according to System.Net.Primitives), a similar gRPC status code (according to Grpc.Core.Api) and a description common to both.
  • WebErrorStatuses

    • Opiniated WebErrorStatus objects that relate error types according to their meaning in the Web;
    • It also relates these Error Statuses with known types of Exceptions - both custom and generic (check Exceptions and matching Status Codes below).

How to use

  1. In your Startup class or similar, add the ToolPack Exception services as below. Use Dependency Injection extension methods according to your case.
public void ConfigureServices(IServiceCollection services)
{
	// If developing a REST Web API
	services.AddToolPackExceptions();
	
	// If developing a gRPC API, use one of the following:
	
	// 1. You may replace the call to "AddToolPackExceptions()" by:
	services.AddToolPackExceptionsGrpc();

	// 2. Alternatively, you may call "AddToolPackExceptions()" and add a global interceptor:
	services
		.AddToolPackExceptions()
		.AddToolPackExceptionsGrpcInterceptor()
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	// If developing a non-gRPC Web API, use this to register a Global Exception Middleware
	app.UseToolPackExceptionsMiddleware();
}
  1. This setup will add middleware handlers to catch exceptions thrown in the application and produce responses based on the ProblemDetails model above. These handlers also map the thrown exceptions with HTTP and RPC status codes, as shown below.

  2. Besides the dependency injection services, all the entities, models and utils described above can be used indiscriminately across the code.

Exceptions and matching Status Codes

  • (Check the class WebErrorStatuses for more details)
Exception Exception Package RPC Status Code HTTP Status Code
AlreadyExistsException ToolPack.Exceptions.Base 6 AlreadyExists 409 Conflict
ArgumentException System 3 InvalidArgument 400 BadRequest
AuthenticationException System.Security.Authentication 16 Unauthenticated 401 Unauthorized
CustomBaseException (none of the others customized) ToolPack.Exceptions.Base 13 Internal 500 InternalServerError
Exception (none of the others) System 2 Unknown 500 InternalServerError
ExternalComponentException ToolPack.Exceptions.Base 13 Internal 424 FailedDependency
HttpRequestException System.Net.Http 14 Unavailable 503 ServiceUnavailable
NotFoundException ToolPack.Exceptions.Base 5 NotFound 404 NotFound
NotImplementedException System 12 Unimplemented 501 NotImplemented
TaskCanceledException System.Threading.Tasks 1 Cancelled 400 BadRequest
TimeoutException System 4 DeadlineExceeded 504 GatewayTimeout
UnauthorizedAccessException System 7 PermissionDenied 403 Forbidden
ValidationFailedException ToolPack.Exceptions.Base 9 FailedPrecondition 400 BadRequest
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.0.0 177 6/5/2022
1.0.0 438 4/10/2022