I have an ASP.NET MVC 2 application with a custom StructureMap controller factory to handle dependency injection for my controllers:
public class StructureMapControllerFactory : DefaultControllerFactory
{
public override IController CreateController(RequestContext context, string controllerName)
{
Type controllerType = base.GetControllerType(context, controllerName);
return ObjectFactory.GetInstance(controllerType) as IController;
}
}
I would like to know how I can handle exceptions in this controller factory so that they can be redirected to the ~/Views/Shared/Error.aspx in the same way as they are in a controller that has the HandleError attribute. Currently exceptions don't do this despite having the CustomErrors attribute set to "On".
At the moment I can generate such an exception using a URL like "~/DoesNotExist/edit/1". With the default route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
MVC matches this route and passes controller name "DoesNotExist" to my controller factory. The GetControllerType then returns null and causes a null reference exception in the call to StructureMap. I would then like to be able to handle this exception.
Note that adding a subsequent catch all route will not resolve this problem - MVC matches the default route.
I know I could solve this particular problem by putting constraints on the default route for controller but the question is more general about how I can use the normal MVC ~/Views/Shared/Error.aspx in the factory.
Note that I don't want the answer to require tight coupling of the controller factory to the particular MVC application. Ideally this factory should be in a referenced assembly not in the same solution.
Another way to handle controller level exceptions is by overriding the OnException() method in the controller class. This method handles all your unhandled errors with error code 500. It allows you to log an exception and redirect to the specific view. It does not require to enable the <customErrors> config in web.
Exception filter in MVC provides an ability to handle the exceptions for all the controller methods at a single location. This is by creating a class, which inherits from the FilterAttribute and IExceptionFilter interface.
Maybe you can adapt this controller factory to handle the exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With