CustomExceptionMiddleware 1.2.0

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

// Install CustomExceptionMiddleware as a Cake Tool
#tool nuget:?package=CustomExceptionMiddleware&version=1.2.0                

Custom Exception Middleware

Github actions status Quality Gate Status Nuget

It is a middleware for error handling in ASP.NET projects, the application aims to facilitate and handle when an accidental or custom exception occurs in the project.

Install

  • Package Manager Console

Install-Package CustomExceptionMiddleware
  • .Net CLI

dotnet add package CustomExceptionMiddleware

Minimum requirements to use: .NET Standard 2.0

Compilation requirements: .NET 6

How to use

It's very simple to use, go to Startup.cs on Configure() method and add this code:

app.UseCustomExceptionMiddleware();

Example output

{
    "type": "VALIDATION_ERRORS",
    "error": {
        "msg": "Custom domain exception message"
    }
}

Custom use

  • Create object options: It's possible create a CustomExceptionOptions to customize the return middleware object, to view the StackTrace like this:

    app.UseCustomExceptionMiddleware(new CustomExceptionOptions
    {
        ViewStackTrace = true
    });
    
  • Use an action options: Other options to customize the return object is using an action to create a CustomErrorModel

    app.UseCustomExceptionMiddleware(options =>
    {
        options.ViewStackTrace = true;
    });
    

In both cases the output will include de stack trace in detail object property:

Example output

{
    "type": "VALIDATION_ERRORS",
    "error": {
        "msg": "Custom domain exception message",
        "detail": "at CustomExceptionMiddleware.WebAppTest.Custom.ProductService.GetDomainException(Boolean returnProducts) in C:\\isaacnborges\\projects\\custom-exception-middleware\\tests\\CustomExceptionMiddleware.WebAppTest.Custom\\ProductService.cs:line 18\r\n   at CustomExceptionMiddleware.WebAppTest.Custom.Controllers.ProductController.GetDomain(Boolean returnProduct) in C:\\isaacnborges\\projects\\custom-exception-middleware\\tests\\CustomExceptionMiddleware.WebAppTest.Custom\\Controllers\\ProductController.cs:line 26"
    },
}

Configure Exceptions

This middleware use some custom exceptions to catch and personalize the response status code.

The custom middleware supports the following Exceptions:

Exception              Status code description  Status code
---------------------  -----------------------  -----------
DomainException        BadRequest                  400        
CannotAccessException  Forbidden                   403        
NotFoundException      NotFound                    404        
Exception              InternalServerError         500        

DomainException is an abstract exception, so to use it's necessary create other exception and inherit. The others exceptions only throw an exception

Custom exception example
public class InvalidStateException : DomainException
{
        public InvalidStateException()
        { }

        public InvalidStateException(string message) : base(message)
        { }

        public InvalidStateException(string message, Exception innerException) : base(message, innerException)
        { }
}
Throw exceptions
throw new InvalidStateException("Custom domain exception message");
throw new CannotAccessException("Custom cannot access exception message");
throw new NotFoundException("Custom not found exception message");
throw new Exception("Custom exception message");
Customize exception type

It's possible to customize the exception type when throw an exception, just pass the type in an exception constructor.

throw new CustomDomainException("Custom domain exception message", "OTHER_CUSTOM_TYPE");

Samples

Inside the samples folder has two projects that could be used for test the and validate the middleware.

Run the sample projects
  • WebAppTest
    dotnet run --project .\samples\CustomExceptionMiddleware.WebAppTest\
    
  • WebAppTest.Custom
    dotnet run --project .\samples\CustomExceptionMiddleware.WebAppTest.Custom\
    
Samples documentation

Logging

This middleware will Log some informations that can be used for monitoring and observability, like TraceIdentifier, request and exception informations like message type and stack trace:

Example log:

Occurred an exception - TraceId: 0HMBO9LGH0JHD:00000002 - ExceptionType: InvalidStateException - Message: Custom domain exception message
CustomExceptionMiddleware.WebAppTest.InvalidStateException: Custom domain exception message
at CustomExceptionMiddleware.WebAppTest.Custom.ProductService.GetDomainException(Boolean returnProducts) in C:\\isaacnborges\\projects\\custom-exception-middleware\\tests\\CustomExceptionMiddleware.WebAppTest.Custom\\ProductService.cs:line 18\r\n   at CustomExceptionMiddleware.WebAppTest.Custom.Controllers.ProductController.GetDomain(Boolean returnProduct) in C:\\isaacnborges\\projects\\custom-exception-middleware\\tests\\CustomExceptionMiddleware.WebAppTest.Custom\\Controllers\\ProductController.cs:line 26

Using custom attribute

In some scenarios the project needs other response object, integrations with 3rd party systems for example, this middleware contains an attribute that could be ignore, it's possible use in class or methods

Using the IgnoreCustomExceptionAttribute attribute the middleware will ignore your own flow. To use it simply, decorate the class or method with the name.

  • Class example

    [IgnoreCustomException]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            throw new CustomDomainException("Some error ignore class");
        }
    
  • Method example

    [IgnoreCustomException]
    [HttpGet("ignore")]
    public IActionResult GetIgnore()
    {
        throw new CustomDomainException("Some error ignore method");
    }
    

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos 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
1.3.0 7,903 12/21/2023
1.2.1 59,916 5/31/2022
1.2.0 5,454 3/22/2022
1.1.7 5,447 12/29/2021
1.1.6 1,295 12/7/2021
1.1.5 8,493 11/23/2021
1.1.0 28,453 9/21/2021 1.1.0 is deprecated because it is no longer maintained.