Handling un handled exception in .Net MVC application with Exception Filter is very easy thing to achieve.
There are ways to achieve
Try/Catch:
Putting our code inside try block and handling code inside catch block is something that every programmer know.
try{//our code}
catch{//handling code}
OnException Method:
Controller class implements the IExceptionFilter.
We can override the OnException Method inside the controller class and can handle.
Attribute Based method:
Create an attribute that implements IExceptionFilter and use it over the method or class.
Global Handle Error:
Create an Handlr error attribute and register in filter config.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ERP.Attributes
{
public class GlobalHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled /*|| !filterContext.HttpContext.IsCustomErrorEnabled*/)
{
return;
}
filterContext.ExceptionHandled = true;
string spMessage = string.Empty;
Exception exception = filterContext.Exception;
if (exception is SqlException)//Get Exception Message raised by Stored procedure
{
SqlErrorCollection collection = (exception as SqlException).Errors;
for (int i = 0; i < collection.Count; i++)
{
if (!string.IsNullOrEmpty(collection[i].Procedure) && collection[i].LineNumber > 0)
{
spMessage = spMessage + collection[i].Message;
}
}
}
if (IsAjax(filterContext) && !IsAcceptTextOrHtml(filterContext))//AJAX Call
{
string message = /*exception.GetType().Name + " : " +*/ (string.IsNullOrEmpty(spMessage) ?filterContext.Exception.Message : spMessage);
filterContext.Result = new JsonResult()
{
Data = new { Success = false, ErrorMessage = message, SuccessMessage = message, Message = message },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else //Normal Call
{
string currentController = filterContext.RouteData.Values["controller"].ToString();
string currentActionName = filterContext.RouteData.Values["action"].ToString();
HandleErrorInfo handleErrorInfo = new HandleErrorInfo(exception, currentController, currentActionName);
filterContext.Result = new ViewResult()
{
ViewName = "~/Views/Shared/GlobalError.cshtml",
ViewData = new ViewDataDictionary(handleErrorInfo),
};
}
base.OnException(filterContext);
}
private bool IsAjax(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["Accept"].ToLower().Contains("application/json") ||
filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest" ||
filterContext.HttpContext.Request.IsAjaxRequest();
}
private bool IsAcceptTextOrHtml(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["Accept"].ToLower().Contains("text/html");
}
}
}
using System.Web;
using System.Web.Mvc;
namespace ERP.WebApp
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new GlobalHandleErrorAttribute());
filters.Add(new GlobalActionFilterAttribute());
}
}
}
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ERP.Attributes
{
public class GlobalHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled /*|| !filterContext.HttpContext.IsCustomErrorEnabled*/)
{
return;
}
filterContext.ExceptionHandled = true;
string spMessage = string.Empty;
Exception exception = filterContext.Exception;
if (exception is SqlException)//Get Exception Message raised by Stored procedure
{
SqlErrorCollection collection = (exception as SqlException).Errors;
for (int i = 0; i < collection.Count; i++)
{
if (!string.IsNullOrEmpty(collection[i].Procedure) && collection[i].LineNumber > 0)
{
spMessage = spMessage + collection[i].Message;
}
}
}
if (IsAjax(filterContext) && !IsAcceptTextOrHtml(filterContext))//AJAX Call
{
string message = /*exception.GetType().Name + " : " +*/ (string.IsNullOrEmpty(spMessage) ?filterContext.Exception.Message : spMessage);
filterContext.Result = new JsonResult()
{
Data = new { Success = false, ErrorMessage = message, SuccessMessage = message, Message = message },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else //Normal Call
{
string currentController = filterContext.RouteData.Values["controller"].ToString();
string currentActionName = filterContext.RouteData.Values["action"].ToString();
HandleErrorInfo handleErrorInfo = new HandleErrorInfo(exception, currentController, currentActionName);
filterContext.Result = new ViewResult()
{
ViewName = "~/Views/Shared/GlobalError.cshtml",
ViewData = new ViewDataDictionary(handleErrorInfo),
};
}
base.OnException(filterContext);
}
private bool IsAjax(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["Accept"].ToLower().Contains("application/json") ||
filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest" ||
filterContext.HttpContext.Request.IsAjaxRequest();
}
private bool IsAcceptTextOrHtml(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["Accept"].ToLower().Contains("text/html");
}
}
}
using System.Web;
using System.Web.Mvc;
namespace ERP.WebApp
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new GlobalHandleErrorAttribute());
filters.Add(new GlobalActionFilterAttribute());
}
}
}