Will's Error handling post is awesome! I'm not yet using ELMAH, but I'd like to start adding some of my own data to the Exception on a per Controller basis. Right now, I have a base controller overriding OnException(ExceptionContext)
as per Will from which all project Controllers inherit.
I think I understand I'll need to customize another OnException
override on each Controller, but how do I pass data into that Exception? The data I need may not always be a single text value.
- Should I throw custom Exceptions?
- Should I throw generic
Exception(string)
exceptions and somehow access them within the override?
Edit
This may sound silly, but is there any way to handle an unhandled error and still mine this information? If not, the only solution I can see is creating the custom Exception instance at the beginning of every Controller method for the remote possibility that it will be needed. Is this the only way?
Another Edit
Per Lost In Tangent's post (and part 2), I modified this CustomFactory class, and registered it in Global.asax. The references in his post to base.requestContext weren't valid.
public class CustomFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
var controller = (Controller)base.GetControllerInstance(requestContext, controllerType);
controller.ActionInvoker =
new CustomControllerActionInvoker(new ControllerContext(requestContext, controller));
return controller;
}
}
Then in my CustomControllerActionInvoker class, I override InvokeAction:
public override bool InvokeAction(ControllerContext controllerContext, string actionName)
{
try
{
return base.InvokeAction(controllerContext, actionName);
}
catch (Exception)
{
throw;
}
}
I think the catch block is where Brian suggests I create a ViewResult, but how do I create the right kind based on which controller it came from?