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.NotFoundmessage);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.OKitem);
    }
}

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives