debugcsharpCritical
ASP.NET Core Web API exception handling
Viewed 0 times
netaspapiwebcoreexceptionhandling
Problem
I am using ASP.NET Core for my new REST API project after using regular ASP.NET Web API for many years. I don't see any good way to handle exceptions in ASP.NET Core Web API. I tried to implement an exception handling filter/attribute:
And here is my Startup filter registration:
The issue I was having is that when an exception occurs in my
So how can I catch all application exceptions as well as any exceptions from Action Filters?
public class ErrorHandlingFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
HandleExceptionAsync(context);
context.ExceptionHandled = true;
}
private static void HandleExceptionAsync(ExceptionContext context)
{
var exception = context.Exception;
if (exception is MyNotFoundException)
SetExceptionResult(context, exception, HttpStatusCode.NotFound);
else if (exception is MyUnauthorizedException)
SetExceptionResult(context, exception, HttpStatusCode.Unauthorized);
else if (exception is MyException)
SetExceptionResult(context, exception, HttpStatusCode.BadRequest);
else
SetExceptionResult(context, exception, HttpStatusCode.InternalServerError);
}
private static void SetExceptionResult(
ExceptionContext context,
Exception exception,
HttpStatusCode code)
{
context.Result = new JsonResult(new ApiResponse(exception))
{
StatusCode = (int)code
};
}
}And here is my Startup filter registration:
services.AddMvc(options =>
{
options.Filters.Add(new AuthorizationFilter());
options.Filters.Add(new ErrorHandlingFilter());
});The issue I was having is that when an exception occurs in my
AuthorizationFilter it's not being handled by ErrorHandlingFilter. I was expecting it to be caught there just like it worked with the old ASP.NET Web API.So how can I catch all application exceptions as well as any exceptions from Action Filters?
Solution
Latest ASP.NET 8+
Implement interface IExceptionHandler. You can inject logger and other dependencies in constructor.
Once you have your IExceptionHandler implementation, simply register this middleware:
Implement interface IExceptionHandler. You can inject logger and other dependencies in constructor.
using Microsoft.AspNetCore.Diagnostics;
class MyExceptionHandler : IExceptionHandler
{
public async ValueTask TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
// Your response object
var error = new { message = exception.Message };
await httpContext.Response.WriteAsJsonAsync(error, cancellationToken);
return true;
}
}Once you have your IExceptionHandler implementation, simply register this middleware:
builder.Services.AddExceptionHandler();
app.UseExceptionHandler(_ => {});- You can add multiple IExceptionHandler implementations, and they will be called in the order of registration.
- Return
truefromTryHandleAsyncif exception is handled, or returnfalseand it will be passed to the next handler.
Code Snippets
using Microsoft.AspNetCore.Diagnostics;
class MyExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
// Your response object
var error = new { message = exception.Message };
await httpContext.Response.WriteAsJsonAsync(error, cancellationToken);
return true;
}
}builder.Services.AddExceptionHandler<MyExceptionHandler>();
app.UseExceptionHandler(_ => {});Context
Stack Overflow Q#38630076, score: 783
Revisions (0)
No revisions yet.