How to add Exception Filter in ASP.NET Core Globally

Exception Handling is an important thing for every application and C# language provides different ways to handle the exception. We can handle exception locally in the method as well as globally but it's not efficient to add a try/catch block in every method as logging the error from every catch block of the method is not efficient as it violates code reuse so efficient way is to add global exception filter which will log all the common errors in the application as well as return custom error message from the backend to the UI so in this way users will not know the code details like method name, class name, etc.. when an error occurs.


In order to add Global Exception in ASP.NET Core, we need to follow the below steps 

Step 1: First we need to create a class that will inherit IExceptionFilter declared in the namespace "Microsoft.AspNetCore.Mvc.Filters" and implement the OnException method of the interface.


public class GlobalExceptionFilters : IExceptionFilter
    {
        private readonly ILogger _logger;


        public GlobalExceptionFilters(ILogger<GlobalExceptionFilters> logger)
        {
            _logger = logger;
        }


        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                var exception = context.Exception;


                int statusCode;


                switch (true)
                {
                    case bool _ when exception is UnauthorizedAccessException:
                        statusCode = (int)HttpStatusCode.Unauthorized;
                        break;


                    case bool _ when exception is InvalidOperationException:
                        statusCode = (int)HttpStatusCode.BadRequest;
                        break;


                    default:
                        statusCode = (int)HttpStatusCode.InternalServerError;
                        break;
                }


                _logger.LogError($"GlobalExceptionFilter: Error in {context.ActionDescriptor.DisplayName}. {exception.Message}. Stack Trace: {exception.StackTrace}");


                // Custom Exception message to be returned to the UI
                context.Result = new ObjectResult(exception.Message) { StatusCode = statusCode };
            }
        }
    }




Step 2: Register the ExceptionFilter in ConfigureServices method in Startup.cs file

 services.AddMvc(options =>
            {
                options.Filters.Add(typeof(GlobalExceptionFilters));
            })


Now the Exception filter is registered the OnException will hit once any exception occurred.

Hope you have enjoyed the article.

Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee