The GlobalExceptionFilter is an attribute designed to handle exceptions globally across your application. By using this filter, you can centralize the logic for handling exceptions, making it easier to manage and maintain.
Key Features
Exception handling: Handles exceptions both synchronously and asynchronously.
Service integration: Integrates with an optional IExceptionHandler service, if available, to delegate the exception handling process. Thus you can build your own exception handling mechanism.
HTTP response mapping: Maps exceptions to their respective HTTP status codes and produces a consistent API response. Specifically for HttpRequestException class.
You should install Eiffel.CrossCutting.ExceptionHandling NuGet package into your application.
Usage
To appy this filter to all controllers in your application, add to Mvc filters.
// Program.cs (.NET5 and above)publicstaticasyncTaskMain(string[] args){var builder =WebApplication.CreateBuilder(args); // Applies api response filter for all controllersbuilder.Services.AddControllers(options => {options.Filters.Add<GlobalExceptionFilter>(); });var app =builder.Build();app.Run();}
Custom exception handling
The IExceptionHandler interface provides a contract for handling exceptions. By implementing this interface, you can provide custom logic to determine the HTTP status code and error message based on different exceptions.