.Net 8 IExceptionHandler

Spread the love

Before this we used to use a filter (GlobalExceptionFilter) to handle exceptions at one place.

.Net 8 has a new IExceptionFilter middleware which can be used to filter the exceptions. For more look at: Handle errors in ASP.NET Core | Microsoft Learn

The new exception handler keeps information in Features property. So, If you face any issue with reading the about the exception e.g. controller then these features will have all the information. On the page that I have mentioned you can see that there are examples of accessing some of these features. I will add some that I have used:

Reading the body:

Enable buffering first:

  app.Use((context, next) =>
  {
      context.Request.EnableBuffering();                
      return next();
  });

Now read in the TryHandleAsync:

 var request = httpContext.Features.Get<IHttpRequestFeature>();

 string requestBody = null;
 if (request != null)
 {
     request.Body.Seek(0, SeekOrigin.Begin);
     requestBody = await new StreamReader(request.Body, encoding: Encoding.UTF8).ReadToEndAsync();
 }

Read controller and method name:

var routeValues = httpContext.Features.Get<IExceptionHandlerFeature>()?.RouteValues;
// we may get controllerName and methodName as null
string? controllerName = null;
string? methodName = null;

if (routeValues != null)
{
    ((RouteValueDictionary)routeValues).TryGetValue("controller", out object? controllerNameObj);
    if (controllerNameObj != null)
    {
        controllerName = (string)controllerNameObj;
    }

    ((RouteValueDictionary)routeValues).TryGetValue("action", out object? methodNameObj);
    if (methodNameObj != null) { methodName = (string)methodNameObj; }
}

Cheers and Peace Out!!!