Exception Handling in ASP.NET Web API

Introduction

In this article, we will define exception handling in the ASP.NET Web API.

Excepting handling is a process that handles an exception by saving the current state of execution and switches the execution to the specific subroutine. The following are used:
  • HttpResponseException
  • Exception Filter
  • Registering Exception Filters
  • HttpError

HttpResponseException

It is a special type of exception. It throws an HTTP code as an exception that is defined in the exception constructor. In it the exception is converted into a HTTP response.

  1. public Detail GetDetail(int Id)  
  2. {  
  3.     Detail item = reposite.Get(Id);  
  4.     if (val == null)  
  5.     {  
  6.         throw new HttpResponseException(HttpStatusCode.NotFound);  
  7.     }  
  8.     return val;  
  9. } 

If there is an Id parameter not defined then it will return the response "NotFound".

We can create own response message for controlling the resoponse, and this message  wille be included with the HttpResponseException.

  1. public Detail GetDetail(int Id)  
  2. {  
  3.     Detail val = reposite.Get(Id);  
  4.     if (item == null)  
  5.     {  
  6.         var show = new HttpResponseMessage(HttpStatusCode.NotFound)  
  7.         {  
  8.             Con = new StringContent(string.Format("There is no Detail with Id {0}", Id)),  
  9.             Reason_Phrase = "Detail Id not defined"  
  10.         }  
  11.         throw new HttpResponseException(Show);  
  12.     }  
  13.     return val;  
  14. } 

Exception Filters:

If there is any Unhandled type exception generated that is not the HttpResponseException type Exception then the Exception filter is used to handle these exceptions. It is written using the Web API.

The "System.Web.Http.Filters.IExceptionFilter" interface and "System.Web.Http.ExceptionFilterAttribute" class are used.

  1. namespace hello.Filters  
  2. {  
  3.     using System;  
  4.     using System.Net;  
  5.     using System.Net.Http;  
  6.     using System.Web.Http.Filters;  
  7.     public class E_Filter : ExceptionFilterAttribute  
  8.     {  
  9.         public override void OnException(HttpActionExecutedContext cont)  
  10.         {  
  11.             if (cont.Exception is NotImplementedException)  
  12.             {  
  13.                 cont.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);  
  14.             }  
  15.         }  
  16.     }  
  17. }   

Registering Exception Filters

We register the exception in various ways that are as follows:

  • Globally

  • By Action

  • By Controller

Globally

When the exception is registered globally, first we need to  create an instance of the GlobalConfiguration.Configuration.Filters.

  1. GlobalConfiguration.Configuration.Filters.Add(new hello.E_Filter());   

If we are working on ASP.NET MVC 4 Application then we add the API configuration code in WebApiConfig.cs class that is located in the App_Start folder.

 

  1. public static class WebApiConfig  
  2. {  
  3.     public static void Register(HttpConfiguration config)  
  4.     {  
  5.         config.Filters.Add(new hello.E_Filter());  
  6.     }  
  7. } 

By Action:

We can also apply a filter for the specific action.

  1. public class DetailController : ApiController  
  2. {  
  3.     [NotImplExceptionFilter]  
  4.     public contact GetContact(int id)  
  5.     {  
  6.         throw new NotImplementedException("method can not be implement");  
  7.     }  
  8. }   

By Controller

We can apply the filter on the all method of a controller.

  1. [NotImplExceptionFilter]  
  2. public class DetailController : ApiController  
  3. {  
  4. } 

HttpError 

HttpError provides a way to show the error message.

  1. public class DetailController : ApiController  
  2. {  
  3.     public HttpResponseMessage GetDetail(int Id)  
  4.     {  
  5.         Detail val = reposite.Get(Id);  
  6.         if (val == null)  
  7.         {  
  8.             var report = string.Format("Id of Detail = {0} ",Id);  
  9.             HttpError error = new HttpError(report);  
  10.             return Request.CreateResponse(HttpStatusCode.NotFound, error);  
  11.         }  
  12.         else  
  13.         {  
  14.             return Request.CreateResponse(HttpStatusCode.OK, val);  
  15.         }  
  16.     }  
  17. } 

We can also use the CreateErrorResponse instead of HttpError.

Let's see an example of CreateErrorResponse:

  1. public class DetailController : ApiController  
  2. {  
  3.     public HttpResponseMessage GetDetail(int Id)  
  4.     {  
  5.         Detail val = reposite.Get(Id);  
  6.         if (val == null)  
  7.         {  
  8.             var report = string.Format("Id of Detail = {0} ",Id);  
  9.             return Request.CreateErrorResponse(HttpStatusCode.NotFound, error);  
  10.         }  
  11.         else  
  12.         {  
  13.             return Request.CreateResponse(HttpStatusCode.OK, val);  
  14.         }  
  15.     }  
  16. }   

This is the description of exception handling.


Similar Articles