Exception Handling in ASP.Net Web API Using Exception Filters

 

To return a HTTP response with a specific error status code, normally a HttpResponseException type is used.

In Part 1 of this article series, we checked a specific condition and returned the relevant error status code. What exactly did we do? We checked if the student object returned from a data source is null, then threw a HttpResponseException with HTTP status code, in other words 404 (Not Found). So, the client will be receiving a meaningful error code instead of a generic code, in other words 500 (Internal Server Error). Please go through Part 1 to understand Exception Handling in ASP.NET Web API using HttpResponseException.

However, there can be other scenarios where the code can generate unhandled exceptions. And for those unhandled exceptions, the client will be receiving the same generic error, in other words "Internal Server Error". In order to tackle such unhandled exceptions, Exception Filters can be used.

Basically, an Exception Filter is a class that implements an IExceptionFilter interface. To handle the unhandled exception scenario decribed above, we can define our own exceptionfilter by creating a class and inheriting it from the ExceptionFilterAttribute class. The implementation for creating a custom Exception Filter is done in the following two simple steps.

  • Registering Exception Filter
  • Creating an Exception Filter class and override the OnException Method.

The following is a custom Web API Exception Filter class.

  1. public class MyCustomExceptionFilter : ExceptionFilterAttribute  
  2. {  
  3.    public override void OnException(HttpActionExecutedContext cntxt)  
  4.    {  
  5.        var exceptionType = cntxt.Exception.GetType();  
  6.        if(exceptionType == typeof(UnauthorizedAccessException))  
  7.        {  
  8.            context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);  
  9.        }  
  10.    }  
  11. } 

The code above is an example of handling an exception using an Exception Filter returning a valid and meaningful response back to the client. I tried to keep it simple but you can add further conditions to check the type of exception and prepare your response accordingly.

Now the second step is to register this custom Exception Filter. We can register an Exception Filter at any of the following levels:

  • Controller Action Level
  • Controller Level
  • Global Level

Let's apply this Exception Filter to our already created ASP.NET Web API Service at various levels. We have a Student Controller having actions for all Create, Retrieve, Update, Delete (CRUD) operations in this HTTP service.

In order to apply to a specific action of the Student controller, we can add our filter "MyCustomExceptionFilter" as an attribute to that specific controller action as follows.

  1. [MyCustomExceptionFilter]  
  2. public Student Get(string id)  
  3. {  
  4.     return StudentRepository.GetStudent(id);  
  5. } 

Similarly, for the controller level, we can add a filter as an attribute to StudentController instead of a specific action of StudentController. Now this will be applicable for all controller actions.

  1. [MyCustomExceptionFilter]  
  2. public class StudentsController : ApiController  
  3. {  
  4.      //Controller detailed code.  
  5. } 

Finally, in order to apply this at the global level, in other words for all Web API controllers, we will do the following:

  1. Create an instance of Exception Filter and
  2. Add to the filters collection in a global configuration.

CRUDWebAPI.MyCustomExceptionFilter ctrlr = new CRUDWebAPI.MyCustomExceptionFilter(); GlobalConfiguration.Configuration.Filters(ctrlr);

In this article, we learned what exception fitlers are and how to create a custom Exception Filter. We also learned how to register it at various levels for handling exceptions in ASP.NET Web API services.

I hope this web application development article will help you in learning exception handling in the ASP.NET Web API.