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
Below worked for me. A few things to note 1) RedirectResult points to a controller action, not a view 2) you need to set filterContext.ExceptionHandled = true; or your exception view / page will not display.
public class ErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
Log.Logger.Error(filterContext.Exception, "An Unhandled exeption occured durring the execution of a request");
filterContext.Result = new RedirectResult("~/MyControler/MyErrorAction");
filterContext.ExceptionHandled = true;
}
}
Ofcourse you will also need to register the Error attribute using the GlobalFilters object from your Global.asax as shown below.
protected void Application_Start()
{
GlobalFilters.Filters.Add(new ErrorAttribute());
...
}