views:

311

answers:

1

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.asax:

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);
+2  A: 

You want to create a customer filter for your controllers / actions. You'll need to inherit from FilterAttribute & 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

HTHs,
Charles

Charlino
ok I'll give this a go. for testing purposes, if I wanted to add it to one of my controllers directly, how would I go about doing that? Sorry for the newbness :/
Kyle
I tried adding the attribute "[CustomExceptionFilter]" To the top of my controller class and then throwing an exception and it doesn't appear to be geting caught by this filter. It's not throwing the same error as before, but it's not hitting my custom exception filter. I also tried putting it on the actionmethod that I'm hitting that should throw the exception, and it's not working there either...any ideas?
Kyle
scratch my last comment, I had forgotten to put my throw back in. When I did, I'm getting the same error as I was before "my exception was unhandled by user code".Do I need it in a try catch?
Kyle
So your `CustomExceptionFilter` is catching it? Or at least firing? What code do you have inside the `if` statement?
Charlino
no. I put a breakpoint in the CustomExceptionFilter and it's never hitting it.I have my [CustomExceptionFilter] attribute at the top of my controller class. I then have an action method that calls a static method outside of the controller class which (currenly) only has "throw new MyCustomException()" to test with. I also tried putting the attribute above that method as well to no avail. It keeps dying and highlighting the "throw new MyCustomException()" line with an error indicating that my exception was unhandled by user code.
Kyle
I assume I set that up correctly based on a few articles that I've read...but for whatever reason, it's never firing my CustomExceptionFilter....
Kyle
I did a quick spike and it all worked fine for me... you'll also need to add `filterContext.ExceptionHandled = true;` into your exception filter, but that won't fix the issue of the filter firing at all. Could you post all the relevant code so I can have a better idea of what could be going wrong. Cheers.
Charlino
// controller class [CustomExceptionFilter] public class SomeController : Controller { public SomeController() { } public ActionResult Index() { SomeClass.SomeStaticMethod(); return View(); } }// SomeClass class public class SomeClass { [CustomExceptionFilter] // added this to test public static void SomeStaticMethod() { throw new MyCustomException("Test from here"); } }// CustomExceptionFilter
Kyle
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { if (filterContext.Exception.GetType() == typeof(MyCustomException)) { // do stuff } } }
Kyle
bah...how do I add code snippets into the comment box here?Sorry for that formatting...not sure how to do that.
Kyle
Thats ok. To put little snippets into comments you surround it with back ticks. But something like what you're trying to post is better put back into your question... so just edit that and add them in there. Can you post the code for _//do stuff_
Charlino
ok I added the redirect logic to what I have inside my if statement. Again though... that never gets reached for some reason.
Kyle