Exception Handling In ASP.NET Web API

Introduction

Exceptions are the errors that happen at runtime. Exception handling is the technique to handle this runtime error in our application code. If any error is thrown in web API that is caught, it is translated into an HTTP response with status code 500- "Internal Server Error".

There are many ways to handle the exception. In this article, I will explain these one-by-one and we will also learn when to use which exception handling method.

Using HttpResponseException

This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor.

For example, the following method of EmployeeController returns Status code 404 (not found), if employee data is not found for ID.

  1. public Employee Get([FromODataUri] int key)  
  2. {  
  3.     Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
  4.     if (data == null)  
  5.     {  
  6.         thrownewHttpResponseException(HttpStatusCode.NotFound);  
  7.     }  
  8.     return data;  
  9. }  
We have more control over the response because we can pass the entire response message (using HttpResponseMessage) to the Constructor of HttpResponseException.
  1. public Employee Get([FromODataUri] int key)  
  2. {  
  3.     Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
  4.   
  5.     if (data == null)  
  6.     {  
  7.         var response = newHttpResponseMessage(HttpStatusCode.NotFound)  
  8.         {  
  9.             Content = newStringContent(string.Format("No Employee found with ID = {0}", key)),  
  10.                 ReasonPhrase = "Employee Not Found"  
  11.         };  
  12.   
  13.         thrownew HttpResponseException(response);  
  14.     }  
  15.     return data;  
  16. }  
HttpResponseException

Using HttpError

CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client. CreateErrorResponse creates an instance of HttpError object and returns it as HttpResponseMessage object.
  1. public HttpResponseMessage Get([FromODataUri] int key)  
  2. {  
  3.     Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
  4.     if (data == null)  
  5.     {  
  6.         string message = string.Format("No Employee found with ID = {0}", key);  
  7.         returnRequest.CreateErrorResponse(HttpStatusCode.NotFound, message);  
  8.     }  
  9.     returnRequest.CreateResponse(HttpStatusCode.OK, data);;  
  10. }  
HttpError

Here, HttpError was serialized into JSON. Here, an error is passed through the same content-negotiation. This is one advantage of using HttpError.

Using Exception Filters

Exception filters can be used to handle unhandled exceptions which are generated in Web API. The exception filter can be able to catch the unhandled exceptions in Web API. This filter is executed when an action method throws the unhandled exception. Note that exception filter does not catch HttpResponseException exception because HttpResponseException is specifically designed to return the HTTP response.

We can use exception filter whenever controller action method throws an unhandled exception that  is not an HttpResponseException. This is an attribute so we can decorate both action method and controller with this. Exception filter is very similar to HandleErrorAttribute in MVC.

The code shown below helps to implement the custom exception filter.
  1. namespace WebAPITest  
  2. {  
  3.     using System.Net;  
  4.     usingSystem.Net.Http;  
  5.     usingSystem.Web.Http.Filters;  
  6.   
  7.     public class CustomExceptionFilter: ExceptionFilterAttribute  
  8.     {  
  9.         public override void OnException(HttpActionExecutedContextactionExecutedContext)  
  10.         {  
  11.             string exceptionMessage = string.Empty;  
  12.             if (actionExecutedContext.Exception.InnerException == null)  
  13.             {  
  14.                 exceptionMessage = actionExecutedContext.Exception.Message;  
  15.             }  
  16.             else  
  17.             {  
  18.                 exceptionMessage = actionExecutedContext.Exception.InnerException.Message;  
  19.             }  
  20.             //We can log this exception message to the file or database.  
  21.             var response = newHttpResponseMessage(HttpStatusCode.InternalServerError)  
  22.             {  
  23.                 Content = newStringContent(“An unhandled exception was thrown by service.”),  
  24.                     ReasonPhrase = "Internal Server Error.Please Contact your Administrator."  
  25.             };  
  26.             actionExecutedContext.Response = response;  
  27.         }  
  28.     }  
  29. }  
Register Exception Filters

There are many ways to register exception filter but the developers generally follow three approaches to register filter.
  • Decorate Action with exception filter.
  • Decorate Controller with exception filter.
  • Filter Register globally.

To apply the exception filter to the specific action, the action needs to decorate with this filter attribute. In the following example, I have applied CustomExceptionFilter filter to only one part of the action.

  1. [CustomExceptionFilter]  
  2. public HttpResponseMessage Get([FromUri]int key)  
  3. {  
  4.    …  
  5.    ….  
  6.    ….  
  7. }  
To apply the exception filter to all the actions of a controller, the controller needs to be decorated with this filter attribute. I the following example, I have applied CustomExceptionFilter filter to EmployeeController class.
  1. [CustomExceptionFilter]  
  2. public class EmployeeController : ApiController  
  3. {  
  4.    …  
  5.    …  
  6.    …  
  7. }  
To apply the exception filter to all Web API controllers, the filter needs to register to GlobalConfiguration.Configuration.Filters collection.
  1. public static class WebApiConfig  
  2. {  
  3.     public static void Register(HttpConfigurationconfig)  
  4.     {  
  5.         config.Filters.Add(newCustomExceptionFilter());  
  6.     }  
  7. }  
Following is a snapshot of Fiddler, when unhandled execution occurred in the action method. We get "An unhandled exception was thrown by service" as a response.

exception

Using Exception Handlers

Normally, exception filter is used to catch the unhandled exception. This approach will work fine but it fails if any error is raised from outside action. For example, if any error is raised in the following area then exception filter will not work.
  • Error inside the exception filter.
  • Exception related to routing.
  • Error inside the Message Handlers class.
  • Error in Controller Constructor.

Exception Handlers

Web API 2 provides a good alternative way to achieve global exception handling. Web API provides "ExceptionHandler" abstract class to handle exception above said area.

Using the following code, we can define the custom implementation of ExceptionHandler.

  1. namespace WebAPITest  
  2. {  
  3.     using System.Net;  
  4.     usingSystem.Net.Http;  
  5.     usingSystem.Threading;  
  6.     usingSystem.Threading.Tasks;  
  7.     usingSystem.Web.Http.ExceptionHandling;  
  8.     usingSystem.Web.Http.Results;  
  9.     publicclassGlobalExceptionHandler: ExceptionHandler  
  10.     {  
  11.         public async override TaskHandleAsync(ExceptionHandlerContext context, CancellationTokencancellationToken)  
  12.         {  
  13.             // Access Exception using context.Exception;  
  14.             conststringerrorMessage = "An unexpected error occured";  
  15.             var response = context.Request.CreateResponse(HttpStatusCode.InternalServerError,  
  16.                 new  
  17.                 {  
  18.                     Message = errorMessage  
  19.                 });  
  20.             response.Headers.Add("X-Error", errorMessage);  
  21.             context.Result = newResponseMessageResult(response);  
  22.         }  
  23.     }  
  24. }  
Same as exception filter, Exception handler is also required to be registered. ExceptionHandler is inheriting from IExceptionHandler interface and Web API has already this type of class registered so we just need to replace this class to our custom exception handler class because Web API doesn’t support multiple ExceptionHandler.
  1. public static class WebApiConfig  
  2. {  
  3.     public static void Register(HttpConfigurationconfig)  
  4.     {  
  5.         config.Filters.Add(new CustomExceptionFilter());  
  6.         config.Services.Replace(typeof(IExceptionHandler), newGlobalExceptionHandler());  
  7.     }  
  8. }  
ExceptionHandler

Summary

Web API supports many ways of exception handling. Following is a summary of exception handling in Web API described in this article:
  • We can use HttpResponseException when the possibility of exception is known by us. In the above example, we have thrown exception using HttpResponseException class as we know there is a chance to employee not found in the database.

  • We can use exception filter to catch unhandled exceptions on action / controllers.

  • We can use Exception Handlers to catch any type of unhandled exception application-wide.