Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle an exception in an ASP.NET MVC controller factory

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.

like image 602
Rob West Avatar asked Sep 30 '10 11:09

Rob West


People also ask

How do you handle exceptions at controller level?

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.

What are the exception filters in MVC?

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.


1 Answers

Maybe you can adapt this controller factory to handle the exceptions.

like image 76
Matt Kocaj Avatar answered Nov 16 '22 22:11

Matt Kocaj