However, there can be other scenarios where the code can generate unhandled exceptions. And for those unhandled exceptions, client will be receiving same generic error i.e. “Internal Server Error”. In order to tackle such unhandled exceptions, Exception Filters can be used.
- Creating Exception Filter class & override OnException Method.
- Registering Exception Filter
Following is a custom Web API exception filter class.
public override void OnException(HttpActionExecutedContext cntxt)
var exceptionType = cntxt.Exception.GetType();
if(exceptionType == typeof(UnauthorizedAccessException))
context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
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.
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 for all controller actions.
//Controller detailed code.
Finally, in order to apply at global level means for all Web API controllers, we will do the following:
- Create an instance of exception filter and
- Add to filters collection in global configuration.
In this article, we learnt
- what exception fitlers 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 API Tutorial will help you in learning exception handling in ASP.NET Web API.
Previous: – Exception Handling in ASP.NET Web API – Part 1
Top 10 Interview Questions and Answers Series:
- Top 10 HTML5 Interview Questions
- Top 10 ASP.NET Interview Questions
- Comprehensive Series of ASP.NET Interview Questions
- Top 10 ASP.NET MVC Interview Questions
- Top 10 ASP.NET Web API Interview Questions
- Top 10 ASP.NET AJAX Interview Questions
- Top 10 WCF Interview Questions
- Comprehensive Series of WCF Interview Questions