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