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);
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;
}
}
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();
Output
Ref: Microsoft
Top comments (0)