Using Exception Filters in ASP.NET Core

Today in this article we will cover how to use Exception Filters in ASP.NET Core.

Today in this article, we will cover below aspects,

Using exception filters is a good technique for centralizing the handling of an exception.

If there is an exception in other layers of your app apart from the API layer then this approach won’t be helpful.

Example – It won’t catch the exception that occurred in the middleware used in the app through the pipeline.

The only limitation of this approach is that it’s effective for only the API pipeline.

I have talked about this technique in detail, please visit the below post for more details.

Let’s look at the example of exception filters using .NET Core.

Getting Started

Let’s create an ASP.NET Core API application.

Create an ASP.NET Core Web API

Please choose ASP.NET Core 3.1 project template.

  • Once the API is created add the class ‘ServiceExceptionInterceptor’ as shown in the below code sample. Below shows examples of handling Synchronous and Asynchronous actions.

  • Please choose the approach that best suits your requirements.

  • The next step is how to enable this exception filter class in the API pipeline.

  • These exception filters can be used at the Global level i.e. Controller level and Method level depending on your requirement.

  • Controlling Filter Global or
    • Controller or
    • The route endpoint level is discussed below in detail.

  • Synchronous: Here you need to derive your filter class from the IExceptionFilter interface and implement OnException.

public class ServiceExceptionInterceptor : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            var error = new ErrorDetails()
            {
                StatusCode = 500,
                Message = "Something went wrong! Internal Server Error."
            };

            //Logs your technical exception with stack trace below
            context.Result = new JsonResult(error);
        }
    }

  • Asynchronous: Here you need to derive your filter class from the IAsyncExceptionFilter interface and implement 1 method OnExceptionAsync,

public class ServiceExceptionInterceptorAsync : IAsyncExceptionFilter
    {

        public Task OnExceptionAsync(ExceptionContext context)
        {
            var error = new ErrorDetails()
            {
                StatusCode = 500,
                Message = $"Something went wrong! Internal Server Error-{context.Exception}"
            };

            //Logs your technical exception with stack trace below
            context.Result = new JsonResult(error);
            return Task.CompletedTask;
        }
    }

Exception Filter – Global

If you want to enable this filter at Controller or want to make it method-specific please see this article on how to achieve the same.

Update Exception Filter Globally in Startup.cs. This way Exception filters will be invoked for all available Controllers in an API.

Use the below code for .NET Core 3.0 and the below version only.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => options.Filters.Add(new 
            ServiceExceptionInterceptor()));
        }

For .NET Core 3.1 and above version

services.AddControllers(options => options.Filters.Add(new
ServiceExceptionInterceptor()));

Exception Filters – Class Level Or Controller Level

Add Exception Filter at Controller or class level can be used as below using TypeFilterAttribute

What is TypeFilter?
TypeFilter is a filter of type Microsoft.AspNetCore.Mvc.TypeFilterAttribute.ImplementationType.
It retrieves missing constructor arguments from dependency injection if available.

Exception Filters – A Endpoint/route Level

Exception Filters can also be added at the Endpoint/route Level,

        [HttpGet]
        [TypeFilter(typeof(ServiceExceptionInterceptorAsync))]
        public IEnumerable<WeatherForecast> Get()
        {

        }

For both above approaches, I have used a simple class for returning a response as below,

Exception Filters in ASP.NET Core

class ServiceExceptionInterceptor Implementation is as below,

Exception code and message

Now let’s test the controller with some exceptions. Error response for most of the exceptions will be generic as below,

blank
Fig REST API response for exception

Other references:

Summary

Today in this article we learned, how to use the ASP.NET Core Exception filter to take care of the core cross-cutting concern i.e. Exception.

There are many types of filters available that could be helpful to take care of the various needs of your application. Filter helps in abstracting your repetitive and important cross-cutting concerns and makes your business logic free of addressing those concerns repeatedly.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.