Global.ExceptionHandler.Net.Core 1.0.0

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

// Install Global.ExceptionHandler.Net.Core as a Cake Tool
#tool nuget:?package=Global.ExceptionHandler.Net.Core&version=1.0.0                

Global.ExceptionHandler.Net.Core

Global Exception Handler Middleware for .NET Core

The Global Exception Handler Middleware for .NET Core is a comprehensive middleware solution designed to enhance the readability and maintainability of your .NET Core web API projects by handling exceptions globally. This middleware eliminates the need for repetitive try-catch blocks in each unit, ensuring a cleaner and more efficient codebase.

Key Features

  • Global Exception Handling: Automatically manages exceptions across your entire application without the need for manual intervention in each endpoint.
  • Exception Types Supported:
    • Server-side Exceptions:
      • BadGatewayException
      • ServiceUnavailableException
      • InternalServerException
    • Client-side Exceptions:
      • BadRequestException
      • ForbiddenException
      • NotFoundException
      • UnauthorizedException
    • Other Exceptions:
      • DomainException
      • BusinessLogicException
  • HTTP Status Code Management: Each exception class includes an appropriate HTTP status code, ensuring accurate error representation and consistency in API responses.
  • Structured API Responses: Generates API responses in a structured format, providing detailed error messages, developer notes, and stack traces when exceptions occur.
  • Logging Integration: Logs exceptions using a customizable logging mechanism (_logger.LogError($"Something went wrong {e.Message}")), facilitating effective monitoring and troubleshooting.

Usage

  1. Install the NuGet package:

    dotnet add package Global.ExceptionHandler.Net.Core
    
  2. Integrate the middleware into your .NET Core application pipeline:

    public class Startup
    {
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseMiddleware<RequestResponseLoggingMiddleware>();
            // Add other middleware registrations here...
        }
    }
    

Example

Here's a simple example of how to use the Global.ExceptionHandler.Net.Core in a .NET Core project:

  1. Create custom exceptions as needed, inheriting from the provided base exceptions:

    public class CustomServerException : ServerException
    {
        public CustomServerException(string message) : base(HttpStatusCode.InternalServerError, message)
        {
        }
    }
    
  2. Use these exceptions in your controllers or services:

    public class SampleController : ControllerBase
    {
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            if (id <= 0)
            {
                throw new CustomServerException("The specified resource was not found.");
            }
    
            return Ok(new { Id = id });
        }
    }
    
  3. Handle NotFoundException as follows:

    public class SampleController : ControllerBase
    {
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            if (id <= 0)
            {
                throw new NotFoundException("The specified resource was not found.");
            }
    
            return Ok(new { Id = id });
        }
    }
    
  4. Use these exceptions in your controllers or services:

    public class SampleController : ControllerBase
    {
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            if (id <= 0)
            {
                throw new CustomNotFoundException("The specified resource was not found.");
            }
    
            return Ok(new { Id = id });
        }
    }
    

Response Example

When an exception like CustomNotFoundException is thrown, the middleware will format the response as follows:

{
  "Error": {
    "Code": 404,
    "DetailedErrors": null,
    "DeveloperMessages": null,
    "Messages": "The specified resource was not found.",
    "StackTrace": null
  },
  "Meta": null,
  "Response": null
}

Supported Constructors

The ServerException class supports the following constructors:

  • ServerException(HttpStatusCode statusCode, string message = null, Exception innerException = null)
  • ServerException(string message)
  • ServerException(string message, Exception innerException)

Get Started

Improve error management in your .NET Core projects today with the Global Exception Handler Middleware. Simplify development, enhance maintainability, and deliver robust APIs effortlessly.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Repository

For more information, please visit the GitHub repository.

Support

If you find this middleware helpful and would like to support its development, consider buying me a coffee!

Buy Me A Coffee

Your support helps in maintaining and improving this middleware. Thank you!

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. 
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.0.0 85 7/3/2024

Initial release