DEV Community

adhakshinamoorthy
adhakshinamoorthy

Posted on

Exception handling in .NET 8: IExecptionHandler

This is an example of how to handle exception globally by implementing IExceptionHandler in .NET 8 Minimal Api

ApiResponse.cs
record ApiResponse(bool Success, string Message);
Enter fullscreen mode Exit fullscreen mode
AppExceptionHandler.cs
using Microsoft.AspNetCore.Diagnostics;

public class AppExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        httpContext.Response.StatusCode = 501;
        httpContext.Response.ContentType = "application/json";
        await httpContext.Response.WriteAsJsonAsync(
            new ApiResponse(false, exception.Message),
            cancellationToken);
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode
Program.cs
var builder = WebApplication.CreateBuilder(args);

// Adds an AppExceptionHandler to services
builder.Services.AddExceptionHandler<AppExceptionHandler>();

var app = builder.Build();

// Adds an exception handling middleware to the pipeline
app.UseExceptionHandler(_ => { });

app.MapGet("api", () =>
{
    throw new ApplicationException("Something went wrong");
});

app.Run();
Enter fullscreen mode Exit fullscreen mode
Output

Image description

Ref: Microsoft

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay