Custome Exception Web API Using ExceptionFilterAttribute In ASP.NET MVC 5


We can custome exception in asp.net mvc 5 like this:

  1. Add new class ExceptionHandlingAttribute.cs

public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is CustomException)
{
var responses = new ApiResponse<object>()
{
Success = false,
ErrorCode = “160”,
ErrorMessage = context.Exception.Message,
Results = null
};
context.Response = context.Request.CreateResponse(HttpStatusCode.OK, responses);

}

var response = new ApiResponse<object>()
{
Success = false,
ErrorCode = “500”,
ErrorMessage = context.Exception.Message,
Results = null
};
context.Response = context.Request.CreateResponse(HttpStatusCode.OK, response);

}
}

  1. Add new class CustomException.cs

[Serializable]
public class CustomException : Exception
{
public CustomException()
: base() { }

public CustomException(string message)
: base(message) { }

public CustomException(string format, params object[] args)
: base(string.Format(format, args)) { }

public CustomException(string message, Exception innerException)
: base(message, innerException) { }

public CustomException(string format, Exception innerException, params object[] args)
: base(string.Format(format, args), innerException) { }

protected CustomException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}

  1. Final add to WebApiConfig.cs

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

How to use it?

throw new CustomException(“Test”);

 

 

 

Advertisements

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 )

Google+ photo

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

Connecting to %s