How to custom exception handling in ASP.NET Core
By Tan Lee Published on Nov 13, 2024 324
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.
- Boost Your ASP.NET Core Website Performance with .NET Profiler
- The name 'Session' does not exist in the current context
- Implementing Two-Factor Authentication with Google Authenticator in ASP.NET Core
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core
- How to Create a custom model validation attribute in ASP.NET Core