In Focus

Global Exception Handling In ASP.NET Core As Exception Filter

This will help the developers to manage the exceptions in the application level and log the respective exception.

While working with enterprise applications, I have seen a lot of problems handling the exceptions properly and logging them respectively. It is always a costly task in .NET if you haven't handled this properly in your application.
 
See the below problems while writing the exceptions,
 
There is a chance child functions are eating exceptions, and parent function is not aware of the exception.
 
While working in layered architecture you have to call multiple nested functions. CLR allows you to throw an exception inside the catch block implicitly so that when you use throw directly inside the catch block, it rethrows the same exception object to the caller preserving the caller stack intact. Now, what does it mean exactly?  See the example below.
  1.         public void ParentFunction()  
  2.         {  
  3.             try  
  4.             {  
  5.                 this.ChildFunction();  
  6.                 Console.WriteLine("After Exception");  
  7.             }  
  8.             catch (Exception ex)  
  9.             {  
  10.             }  
  11.         }  
  12.   
  13.         public void ChildFunction()  
  14.         {  
  15.             try  
  16.             {  
  17.                 this.GrandChildFunction();  
  18.                 Console.WriteLine("Child Function");  
  19.             }  
  20.             catch (Exception ex)  
  21.             {  
  22.                 throw ex;  
  23.             }  
  24.         }  
  25.   
  26.         public void GrandChildFunction()  
  27.         {  
  28.             try  
  29.             {  
  30.                 int x = 10, y = 0;  
  31.                 Console.WriteLine(x / y);  
  32.                 Console.WriteLine("Grand Child Function");  
  33.             }  
  34.             catch (Exception ex)  
  35.             {  
  36.                 throw;  
  37.             }  
  38.         }  

In the above code, parent function is calling child function and child function is calling grandchild function internally. The exception is actually happening in the grandchild level, same as throwing to its parent, which is child function. But child function, wrapped with the exception object, is throwing to its parent. In this scenario, the actual stack trace is lost.

Finding the hidden exceptions
 
It is very common for code like this below to be used within applications. The below code can throw thousands of exceptions a minute and nobody would ever know it. Exceptions will occur if the reader is null, columnName is null, column name does not exist in the results, the value for the column was null, or if the value was not a proper DateTime. But unfortunately, we never get the exact exception. If an exception occurs we will always get a null value.
  1.       public DateTime? GetDateTime(SqlDataReader reader, string columnName)  
  2.         {  
  3.             DateTime? value = null;  
  4.             try  
  5.             {  
  6.                 value = DateTime.Parse(reader[columnName].ToString());  
  7.             }  
  8.             catch  
  9.             {  
  10.             }  
  11.             return value;  
  12.         }  

Extra overhead to manage the bad code

Exception handling in each separate method is always a costly task because it requires time to review the code, refactor the code and make sure all exceptions are handled perfectly. Also, we need to make sure the code is unit tested properly. Also, it is very difficult to manage to log the exceptions in the different environment. Also if multiple developers are working on a solution they will write their own exception to handle the scenarios. 
 
To overcome all the problems, it is better to handle the predefined exceptions and the custom exceptions in a central location as a middleware. Please see the below steps to handle it in ASP.NET Core.
 
Step 1
 
Create a new class called CustomExceptionHandler inside your solution by inheriting IExceptionFilter class. If you want you can create a utility folder and keep it.
  1.     /// <summary>  
  2.     /// This class is used for handle the custom exception in the application level.  
  3.     /// </summary>  
  4.     public class CustomExceptionHandler : IExceptionFilter  
  5.     {  
  6.         public void OnException(ExceptionContext context)  
  7.         {  
  8.             throw new NotImplementedException();  
  9.         }  
  10.     }  
Step 2
 
Create another class called CustomException inside the same namespace as below. Here, I have overloaded the constructor with different parameters to call the base class parameterized constructor.
  1.     /// <summary>  
  2.     /// This class will allow to generate the custom exception message.  
  3.     /// </summary>  
  4.     public class CustomException : Exception  
  5.     {  
  6.         public CustomException()  
  7.         {  
  8.         }  
  9.   
  10.         public CustomException(string message) : base(message)  
  11.         {  
  12.         }  
  13.   
  14.         public CustomException(string message, string responseModel) : base(message)  
  15.         {  
  16.         }  
  17.   
  18.         public CustomException(string message, Exception innerException) : base(message, innerException)  
  19.         {  
  20.         }  
  21.     }  
Step 3
 
Create an enum called Exceptions for sample exceptions.
  1.     /// <summary>  
  2.     /// Different types of exceptions.  
  3.     /// </summary>  
  4.     public enum Exceptions  
  5.     {  
  6.         NullReferenceException = 1,  
  7.         FileNotFoundException = 2,  
  8.         OverflowException = 3,  
  9.         OutOfMemoryException = 4,  
  10.         InvalidCastException = 5,  
  11.         ObjectDisposedException = 6,  
  12.         UnauthorizedAccessException = 7,  
  13.         NotImplementedException = 8,  
  14.         NotSupportedException = 9,  
  15.         InvalidOperationException = 10,  
  16.         TimeoutException = 11,  
  17.         ArgumentException = 12,  
  18.         FormatException = 13,  
  19.         StackOverflowException = 14,  
  20.         SqlException = 15,  
  21.         IndexOutOfRangeException = 16,  
  22.         IOException = 17  
  23.     }  
Step 4
 
Create a private method to get the exact HTTP status code based on the exception inside the CustomExceptionHandler class.
  1.         /// <summary>  
  2.         /// This method will return the status code based on the exception type.  
  3.         /// </summary>  
  4.         /// <param name="exceptionType"></param>  
  5.         /// <returns>HttpStatusCode</returns>  
  6.         private HttpStatusCode getErrorCode(Type exceptionType)  
  7.         {  
  8.             Exceptions tryParseResult;  
  9.             if (Enum.TryParse<Exceptions>(exceptionType.Name, out tryParseResult))  
  10.             {  
  11.                 switch (tryParseResult)  
  12.                 {  
  13.                     case Exceptions.NullReferenceException:  
  14.                         return HttpStatusCode.LengthRequired;  
  15.   
  16.                     case Exceptions.FileNotFoundException:  
  17.                         return HttpStatusCode.NotFound;  
  18.   
  19.                     case Exceptions.OverflowException:  
  20.                         return HttpStatusCode.RequestedRangeNotSatisfiable;  
  21.   
  22.                     case Exceptions.OutOfMemoryException:  
  23.                         return HttpStatusCode.ExpectationFailed;  
  24.   
  25.                     case Exceptions.InvalidCastException:  
  26.                         return HttpStatusCode.PreconditionFailed;  
  27.   
  28.                     case Exceptions.ObjectDisposedException:  
  29.                         return HttpStatusCode.Gone;  
  30.   
  31.                     case Exceptions.UnauthorizedAccessException:  
  32.                         return HttpStatusCode.Unauthorized;  
  33.   
  34.                     case Exceptions.NotImplementedException:  
  35.                         return HttpStatusCode.NotImplemented;  
  36.   
  37.                     case Exceptions.NotSupportedException:  
  38.                         return HttpStatusCode.NotAcceptable;  
  39.   
  40.                     case Exceptions.InvalidOperationException:  
  41.                         return HttpStatusCode.MethodNotAllowed;  
  42.   
  43.                     case Exceptions.TimeoutException:  
  44.                         return HttpStatusCode.RequestTimeout;  
  45.   
  46.                     case Exceptions.ArgumentException:  
  47.                         return HttpStatusCode.BadRequest;  
  48.   
  49.                     case Exceptions.StackOverflowException:  
  50.                         return HttpStatusCode.RequestedRangeNotSatisfiable;  
  51.   
  52.                     case Exceptions.FormatException:  
  53.                         return HttpStatusCode.UnsupportedMediaType;  
  54.   
  55.                     case Exceptions.IOException:  
  56.                         return HttpStatusCode.NotFound;  
  57.   
  58.                     case Exceptions.IndexOutOfRangeException:  
  59.                         return HttpStatusCode.ExpectationFailed;  
  60.   
  61.                     default:  
  62.                         return HttpStatusCode.InternalServerError;  
  63.                 }  
  64.             }  
  65.             else  
  66.             {  
  67.                 return HttpStatusCode.InternalServerError;  
  68.             }  
  69.         }  

In the above method, I have mapped the exceptions to relevant status codes. This is just a sample. You can use your own mapping based on your requirement.

Step 5
 
Implement the OnException method of the parent interface like below. 
  1.         /// <summary>  
  2.         /// This method will automatically trigger when any exception occurs in application level.  
  3.         /// </summary>  
  4.         /// <param name="context"></param>  
  5.         public void OnException(ExceptionContext context)  
  6.         {  
  7.             HttpStatusCode statusCode = (context.Exception as WebException != null && 
  8.                         ((HttpWebResponse) (context.Exception as WebException).Response) != null) ?  
  9.                          ((HttpWebResponse) (context.Exception as WebException).Response).StatusCode  
  10.                          : getErrorCode(context.Exception.GetType());  
  11.             string errorMessage = context.Exception.Message;  
  12.             string customErrorMessage = Constant.ERRORMSG;  
  13.             string stackTrace = context.Exception.StackTrace;  

  14.             HttpResponse response = context.HttpContext.Response;  
  15.             response.StatusCode = (int) statusCode;  
  16.             response.ContentType = "application/json";  
  17.             var result = JsonConvert.SerializeObject(  
  18.                 new  
  19.                 {  
  20.                     message = customErrorMessage,  
  21.                     isError = true,  
  22.                     errorMessage = errorMessage,  
  23.                     errorCode = statusCode,
  24.                     model = string.Empty  
  25.                 });  
  26.             #region Logging  
  27.             //if (ConfigurationHelper.GetConfig()[ConfigurationHelper.environment].ToLower() != "dev")  
  28.             //{  
  29.             //    LogMessage objLogMessage = new LogMessage()  
  30.             //    {  
  31.             //        ApplicationName = ConfigurationHelper.GetConfig()["ApplicationName"].ToString(),  
  32.             //        ComponentType = (int) ComponentType.Server,  
  33.             //        ErrorMessage = errorMessage,  
  34.             //        LogType = (int) LogType.EventViewer,  
  35.             //        ErrorStackTrace = stackTrace,  
  36.             //        UserName = Common.GetAccNameDev(context.HttpContext)  
  37.             //    };  
  38.             //    LogError(objLogMessage, LogEntryType.Error);  
  39.             //}  
  40.             #endregion Logging  
  41.             response.ContentLength = result.Length;  
  42.             response.WriteAsync(result);  
  43.         }  

In the above method I have commented a region called logging which is used for logging in event viewer in my application. You can use your own logging mechanism,

  1. HttpStatusCode is used to get the exact status code for all web exceptions and customized exceptions.
  2. ErrorMessage is used for storing the exact error message.
  3. CustomErrorMessage is used to return the customized error message, here I have used as constant.
  4. StackTrace is used to log the stack trace of the exception, which will be helpful for troubleshooting the issue for the developers.
  5. The response is used for returning the response to the client.
  6. By using JsonConvert class you can serialize the response model into JSON which you need to write to respond. You can wrap up your own response format based on your need. 
Step 6
 
In the startup.cs file please register the exception filter in ConfigureServices method like below.
  1.         /// <summary>  
  2.         /// This method gets called by the runtime. Use this method to add services to the container.  
  3.         /// </summary>  
  4.         /// <param name="services"></param>  
  5.         public void ConfigureServices(IServiceCollection services)  
  6.         {  
  7.             // Add CORS to the web api application  
  8.             AppStart.RegisterCORS(ref services);  
  9.             // Add framework services.  
  10.             services.AddMvc(  
  11.                 config =>  
  12.                 {  
  13.                     config.Filters.Add(typeof(CustomExceptionHandler));  
  14.                     config.Filters.Add(typeof(ValidationFilter));  
  15.                 }  
  16.             ).AddFluentValidation();  
  17.             // Register custom services  
  18.             AppStart.RegisterDIClasses(ref services);  
  19.             AppStart.RegisterSwagger(ref services);  
  20.             AppStart.ConfigureModelValidation(ref services);  
  21.         }  
This is a one time setup in your project, no need to write the exception in all methods. Now, you will be free from writing the exceptions. Please mention in the comment section if you have any concerns.