How to implement the custom error handling in Web API 2.0 ? (Part 6)


This is the continuous post of previous article.There are so many approach to implement the exception in asp.net Web api but In this post we will see how to implement the custom exception handling in asp.net web api 2.0.

Step 1: Create one folder i.e. Helper in asp.net Web api project and add the class and write the code like this

using System;

namespace WebApi_Sample.CustomFilterHelper
{
    public class CatchException:Exception
    {
        public CatchException(string message)
           : base(message)
        {

        }
    }
}

Step 2: Create other class i.e ProcessExceptionFilterAttribute and add the code like this

using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;

namespace WebApi_Sample.CustomFilterHelper
{
    public class ProcessExceptionFilterAttribute : ExceptionFilterAttribute, IExceptionFilter
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            //Check the Exception Type
            if (actionExecutedContext.Exception is CatchException)
            {
                //The Response Message Set by the Action During Ececution
                var res = actionExecutedContext.Exception.Message;

                //Define the Response Message
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(res),
                    ReasonPhrase = res
                };
                //Create the Error Response
                actionExecutedContext.Response = response;
            }
        }
    }
}

Step 3: Now implement the custom exception in web api method like this

Step 4: Execute the Web Api method using Post Man, you will get the exception detail like given below

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.