Click here to Skip to main content
13,451,047 members (49,048 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


6 bookmarked
Posted 6 Feb 2014

Exception Handling in ASP.NET Web API - Part 2

, 6 Feb 2014
Rate this:
Please Sign up or sign in to vote.
Exception handling in ASP.NET Web API - Part 2

In order to return HTTP Response with a specific error status code, normally HttpResponseException type is used. In Part 1 of this article, we checked a specific condition and return error status code accordingly. What exactly did we do? We checked if student object returned from a data source is null, then throw HttpResponseException with HTTP status code, i.e. 404 (Not Found). So, the client will be receiving a meaningful error code instead of generic code, i.e., 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, client will be receiving the same generic error i.e. "Internal Server Error". In order to tackle such unhandled exceptions, Exception Filters can be used.

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

  • Creating Exception Filter class & override OnException Method
  • Registering Exception Filter

Following is a custom Web API exception filter class.

public class MyCustomExceptionFilter : ExceptionFilterAttribute
   public override void OnException(HttpActionExecutedContext cntxt)
         var exceptionType = cntxt.Exception.GetType();
         if(exceptionType == typeof(UnauthorizedAccessException))
               context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);

The above code is an example of handling exception using exception filter returning a valid and meaningful response back to 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 exception filter at different levels,  i.e.:

  • Controller Action Level
  • Controller Level
  • Global Level

Let's apply this exception filter to our already created ASP.NET Web API Service at different levels. We have a Student Controller having actions for all CRUD (Create, Retrieve, Update, Delete) operations in this HTTP service. In order to apply to a specific action of Student controller, we can add our filter "MyCustomExceptionFilter" as an attribute to that particular controller action as follows:

public Student Get(string id)
      return StudentRepository.GetStudent(id);

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

public class StudentsController : ApiController
     //Controller detailed code.

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

  1. Create an instance of exception filter and
  2. Add to filters collection in global configuration
CRUDWebAPI.MyCustomExceptionFilter ctrlr = new CRUDWebAPI.MyCustomExceptionFilter(); 

In this article, we learned what exception filters are? How to create a custom exception filter? and how to register it at different 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 ASP.NET Web API.

Previous: Exception Handling in ASP.NET Web API - Part 1

More Related Articles


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Imran Abdul Ghani
Software Developer (Senior) Emaratech
United Arab Emirates United Arab Emirates
Imran Abdul Ghani has more than 10 years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET(MCSD.NET) since 2005. You can reach his blogging at WCF Tutorials, Web Development, SharePoint for Dummies.

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01-2016 | 2.8.180318.3 | Last Updated 6 Feb 2014
Article Copyright 2014 by Imran Abdul Ghani
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid