Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect asp.net mvc if custom exception is thrown

I need to globally redirect my users if a custom error is thrown in my application. I have tried putting some logic into my global.asax file to search for my custom error and if it's thrown, perform a redirect, but my application never hits my global.asax method. It keeps giving me an error that says my exception was unhandled by user code.

here's what I have in my global.

protected void Application_Error(object sender, EventArgs e)
{
    if (HttpContext.Current != null)
    {
        Exception ex = HttpContext.Current.Server.GetLastError();
        if (ex is MyCustomException)
        {
            // do stuff
        }
    }
}

and my exception is thrown as follows:

if(false)
    throw new MyCustomException("Test from here");

when I put that into a try catch from within the file throwing the exception, my Application_Error method never gets reached. Anyone have some suggestions as to how I can handle this globally (deal with my custom exception)?

thanks.

1/15/2010 edit: Here is what is in // do stuff.

RequestContext rc = new RequestContext(filterContext.HttpContext, filterContext.RouteData);
string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "Home", action = "Index" })).VirtualPath;
filterContext.HttpContext.Response.Redirect(url, true);
like image 928
Kyle Avatar asked Jan 14 '10 20:01

Kyle


1 Answers

You want to create a customer filter for your controllers / actions. You'll need to inherit from FilterAttribute and IExceptionFilter.

Something like this:

public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception.GetType() == typeof(MyCustomException))
        {
            //Do stuff
            //You'll probably want to change the 
            //value of 'filterContext.Result'
            filterContext.ExceptionHandled = true;
        }
    }
}

Once you've created it, you can then apply the attribute to a BaseController that all your other controllers inherit from to make it site wide functionality.

These two articles could help:

  • Filters in ASP.NET MVC - Phil Haack
  • Understanding Action Filters
like image 174
Charlino Avatar answered Oct 22 '22 18:10

Charlino