How i can implement Exception Filters in MVC5.
I want to throw the exception to NLog and redirect the page to a default error page which displays \"Something is gone
Exception filters are run only when unhandled exception has been thrown inside an action method. As you asked, here is an example to redirect to another page upon exception:
public class MyExceptionAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if(!filterContext.ExceptionHandled)
{
filterContext.Result = new RedirectResult("~/Content/ErrorPage.html");
filterContext.ExceptionHandled = true;
}
}
}
Now, to apply this filter to either controllers or individual actions, put [MyException] on them.
You may need to check the occurence of an specific Exception inside the if clause. e.g.:
if(... && filterContext.Excaption is ArgumentOutOfRangeException)
To return a View as Exception Response:
filterContext.Result = new RedirectResult("/Home/ErrorAction");
other alternatives you might use to redirect are: