How to custom exception handling in ASP.NET Core
By FoxLearn 11/13/2024 7:18:00 AM 100
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.
- How to enable CORS in ASP.NET Core WebAPI
- How to fix 'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer'
- Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager'
- HTTP Error 500.30 ASP.NET Core app failed to start
- How to Use IExceptionHandler in ASP.NET Core
- How to create a custom AuthorizeAttribute in ASP.NET Core
- How to manually resolve a type using the ASP.NET Core MVC
- Differences Between AddTransient, AddScoped, and AddSingleton