# Global exception handling

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.

#### Installation

```bash
dotnet add package Eiffel.CrossCutting.ExceptionHandling
```

You should install **Eiffel.CrossCutting.ExceptionHandling** NuGet package into your application.&#x20;

#### Usage

To appy this filter to all controllers in your application, add to Mvc filters.

```csharp
// Program.cs (.NET5 and above)
public static async Task Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    
    // Applies api response filter for all controllers
    builder.Services.AddControllers(options =>
    {
        options.Filters.Add<GlobalExceptionFilter>();
    });
     
    var app = builder.Build();
    app.Run();
}
```

#### Custom exception handling&#x20;

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.

```csharp
/// <summary>
/// Exception handler
/// </summary>
public interface IExceptionHandler
{
    /// <summary>
    /// Handle synchronously operation exceptions 
    /// </summary>
    /// <param name="exception">Exception</param>
    /// <returns>HttpStatusCode, ErrorMessage tuple</returns>
    Tuple<HttpStatusCode, string> Handle(Exception exception);

    /// <summary>
    /// Handle asynchronously operation exceptions
    /// </summary>
    /// <param name="exception">Exception</param>
    /// <returns>HttpStatusCode, ErrorMessage tuple</returns>
    Task<Tuple<HttpStatusCode, string>> HandleAsync(Exception exception);
}
```

Example exception handler

```csharp
public class CustomExceptionHandler : IExceptionHandler
{
    public Tuple<HttpStatusCode, string> Handle(Exception exception) 
    {
        // Your implementation details.. (logging, localization etc.)
        
        // Return HTTP status code and error message
        return new Tuple<HttpStatusCode, string>(statusCode, errorMessage);
    }
    
    public async Task<Tuple<HttpStatusCode, string>> HandleAsync(Exception exception)
    {
        // Your implementation details.. (logging, localization etc.)
        
        // Return HTTP status code and error message
        return new Tuple<HttpStatusCode, string>(statusCode, errorMessage);
    }
}
```

After implementation you should register exception handler class.

```csharp
// Program.cs (.NET5 and above)
public static async Task Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    
    // Register your custom exception handler
    builder.Services.AddSingleton<IExceptionHandler, CustomExceptionHandler>();
     
    var app = builder.Build();
    app.Run();
}
```
