How to custom exception handling in ASP.NET Core

By FoxLearn 11/13/2024 7:18:00 AM   131
To implement custom exception handling using the IExceptionHandler interface in ASP.NET Core, follow these steps.

In November 2023, ASP.NET Core 8 introduced a new preferred path for exception handling using the IExceptionHandler interface.

For example:

using Microsoft.AspNetCore.Diagnostics;

class CustomExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext, 
        Exception exception, 
        CancellationToken cancellationToken)
    {
        // Your response object
        var error = new { message = exception.Message };
        await context.Response.WriteAsJsonAsync(error, cancellation);
        return true;
    }
}

Once you've implemented your custom IExceptionHandler, the next step is to register it as middleware in the ASP.NET Core request pipeline.

builder.Services.AddExceptionHandler<CustomExceptionHandler>();
app.UseExceptionHandler(_ => {});

In ASP.NET Core 8, to make the AddExceptionHandler work properly, you must call UseExceptionHandler in the request pipeline.

For ASP.NET Core 5 version:

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;    
    await context.Response.WriteAsJsonAsync(new { error = exception.Message });
}));

Older versions

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;    
    var result = JsonConvert.SerializeObject(new { error = exception.Message });
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(result);
}));

When adding custom exception handling middleware in ASP.NET Core 3, ensure it is registered before MapControllers, UseMvc, or UseRouting in the request pipeline.

The order of middleware is important because ASP.NET Core processes requests sequentially.