views:

905

answers:

6

I have a base controller class where I'm overriding to the Controller.OnException handler method in order to provide a generic error handling for certain types of controllers that will inherit from this class (these are API controllers that will return JSON results). The OnException method never gets called when an exception gets raised by the controller. Does anyone see what I am doing wrong, or is there a better way to handle this situation?

Using MVC 1.0

Base Class:

public class APIController : Controller
    {

        protected override void OnException(ExceptionContext filterContext)
        {
           //This is never called
            filterContext.Result =
                new JsonResult(); 
            base.OnException(filterContext);
        }


    }

Inheriting Class:

public class MyController : APIController
    {
public AjaxResult ForcedException()
        {
            throw new SystemException();
        }
}
A: 

you might need the [HandleError] attribute applied to the class?

Razvan Dimescu
A: 

See also:

[HandleError] attribute does not seem to act at all… http://stackoverflow.com/questions/524905/handleerror-attribute-does-not-seem-to-act-at-all

Robert Harvey
+2  A: 

If I understand your question correctly - your Exception must be marked as "handled" in your OnException? Try this:

filterContext.ExceptionHandled = true;
eu-ge-ne
this worked for me
benpage
A: 

The MSDN documentation (http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onexception.aspx) states that the OnException method is "called when an unhandled exception occurs in the action."

So, it sounds like it might only fire when an unhandled exception happens in an action method.

I created an new controller with one Index action. And the OnException method does in fact execute. I also tried throwing a SystemException() and the OnException method fired as well.

    public ActionResult Index ( )
    {
        throw new NotImplementedException ( );
    }
phokus
A: 

Are you calling the controller action from a unit test, or via ASP.NET? If you're calling the method directly in a test, say through NUnit, then OnException won't fire: the test framework will handle the exception and turn it into a failed test.

Seth Petry-Johnson
A: 

As far as I can tell, this should work..even without [HandleError]. I can't get this to not work. Can you duplicate this in a new, vanilla project?

SanjayU