Reputation: 151
I am using one MVC application where i have to handle all exception occurs in the code. I have found about exception filter and implemented there. Below is the created exception filter code:
public class HandleException : HandleErrorAttribute
{
#region Log Initialization
FileLogService logService = new
FileLogService(typeof(HandleException));
#endregion
public override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
Log(filterContext.Exception);
base.OnException(filterContext);
}
private void Log(Exception exception)
{
logService.Error(exception.ToString());
}
}
Now i used this filter as attribute in my controller like below:
[AuthSession]
[HandleException]
public class OrganizationalController : BaseController
{
public ActionResult OrgSummary()
{
try
{
int a = 1, b = 0;
int result = a / b;
}
catch (Exception ex)
{
throw ex;
}
ViewData["ShowGrid"] = false;
return View();
}
}
As you can see in above code i am trying to generate exception in the code. In catch exception block when i used throw keyword then exception filter getting executed else not.
Now i need here when any exception occurs in the application i need to show a custom popup message for user. In popup message once user click on ok button then user should be available on the same page. The page should not break or get blank.
How could i implement this functionality?
Upvotes: 0
Views: 417
Reputation: 71
Try this code. May be it helps
public class MyExceptionFilter: FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// below code will redirect to the error view
filterContext.Result = new RedirectResult("ErrorPage.html");
filterContext.ExceptionHandled = true;
}
}
and then you need to apply the above as an attribute to your action methods like:
[MyExceptionFilter]
public ActionResult XYZ()
{
}
Upvotes: 1