How do I add my own data to an Exception in MVC?
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(controllerCon开发者_StackOverflowtext, 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?
If you want to add additional information to the logged message, create a custom exception and add additional properties for information you want to collect. Some loggers log the ToString() method return call, or only log the message, so I don't know what ELMAH does. Most probably do ToString(), so if in the exception you override ToSTring() to add the additional information there, that should be added to the message logged.
精彩评论