Thursday, 15 November 2018

Exception Handling in Web API

Exception Handling in ASP.NET Web API
There are many ways to handle the exception.
  1. HttpResponseException
  2. Exception Filters
  3. HttpError
HttpResponseException: This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor.

public Product GetProduct(int id{
    Product item = repository.Get(id);
if (item == null)
    {
throw new HttpResponseException(HttpStatusCode.NotFound);
    }
return item;
}

Exception Filters: You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response. Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface.
The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method.

public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
    {
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotImplementedException)
            {
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            }
        }
    }

Register Exception Filters
There are many ways to register exception filter but the developers generally follow three approaches to register filter.
  1. Decorate Action with exception filter.
  2. Decorate Controller with exception filter.
  3. Filter Register globally.
To apply the filter to a specific action, add the filter as an attribute to the action:

public class ProductsController : ApiController { [NotImplExceptionFilter] public Contact GetContact(int id) { throw new NotImplementedException("This method is not implemented"); } }


To apply the filter to all of the actions on a controller, add the filter as an attribute to the controller class:

[NotImplExceptionFilter] public class ProductsController : ApiController { // ... }

To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration.Configuration.Filters collection. Exeption filters in this collection apply to any Web API controller action.

public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute()); // Other configuration code... } }

HttpError: CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client.

public HttpResponseMessage GetProduct(int id{
    Product item = repository.Get(id);
if (item == null)
    {
var message = string.Format("Product with id = {0} not found", id);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
    }
else
    {
return Request.CreateResponse(HttpStatusCode.OK, item);
    }
}

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (26) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (8) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (13) Web Api (9) Web Service (1) XMl (1)