Tuesday, 28 June 2016

Web API: Create an attribute to handle all the api exceptions.

To avoid the try catch in each and every controller I have created an attribute that handles all the api exceptions in one place. I have create HandleApiExceptionAttribute class that is inherited from ExceptionFilterAttribute. It overrides the OnExceptionAsync method of ExceptionFilterAttribute class. This method fires everytime when any exception occured in the application.

Step 1: Create new HandleApiExceptionAttribute.cs class and inherit it from ExceptionFilterAttribute. Now write the following code in that class.

public class HandleApiExceptionAttribute : ExceptionFilterAttribute
    {
        public override async Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            var request = actionExecutedContext.ActionContext.Request;
                     
            actionExecutedContext.Response = request.CreateResponse(HttpStatusCode.InternalServerError, actionExecutedContext.Exception.Message);
        }
    }

Step 2: The following code is for handle the exceptions in only for that controller on which this "HandleApiException" attribute applied.

    /// <summary>
    /// Account controller
    /// </summary>
    [RoutePrefix("api/Account")]
    [HandleApiException]    
    public class AccountController : BaseController
    {
    }

For handle the execptions in all the api controllers we can add this attribute in WebApiConfig.cs file. Please check code below:

Add following line in Register method of WebApiConfir.cs file.

config.Filters.Add(new HandleApiExceptionAttribute());

Example:
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Filters.Add(new HandleApiExceptionAttribute());
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

No comments:

Post a Comment