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: Simply integrate the middleware into your .NET Core application pipeline to benefit from seamless exception handling and standardized error responses across your entire API. 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.
$ dotnet add package Global.ExceptionHandler.Net.CoreGlobal 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.
BadGatewayExceptionServiceUnavailableExceptionInternalServerExceptionBadRequestExceptionForbiddenExceptionNotFoundExceptionUnauthorizedExceptionDomainExceptionBusinessLogicException_logger.LogError($"Something went wrong {e.Message}")), facilitating effective monitoring and troubleshooting.Install the NuGet package:
dotnet add package Global.ExceptionHandler.Net.Core
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...
}
}
Here's a simple example of how to use the Global.ExceptionHandler.Net.Core in a .NET Core project:
Create custom exceptions as needed, inheriting from the provided base exceptions:
public class CustomServerException : ServerException
{
public CustomServerException(string message) : base(HttpStatusCode.InternalServerError, message)
{
}
}
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 });
}
}
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 });
}
}
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 });
}
}
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
}
The ServerException class supports the following constructors:
ServerException(HttpStatusCode statusCode, string message = null, Exception innerException = null)ServerException(string message)ServerException(string message, Exception innerException)Improve error management in your .NET Core projects today with the Global Exception Handler Middleware. Simplify development, enhance maintainability, and deliver robust APIs effortlessly.
This project is licensed under the MIT License - see the LICENSE file for details.
For more information, please visit the GitHub repository.
If you find this middleware helpful and would like to support its development, consider buying me a coffee!
Your support helps in maintaining and improving this middleware. Thank you!