views:

38

answers:

1

What's the best way to handle exceptions that happen from within a controller's constructor?

All I can think of to do is use Application_OnError() or put a try/catch in my ControllerFactory.

Neither of these solutions seem ideal. Application_OnError is to broad - I have some non-mvc content in the site that has its own error handling.

Using a try/catch block seems kinda hacky.

If I'm serving different content type -html/text/json/rss.... I would like to be able to handle the exception from within the action method instead of having to write all kinds of conditions to determine what kind of error message to serve.

Am I missing something here, or has anyone else dealt with this?

+1  A: 

If an exception is happening in your ControllerFactory when creating the controller in the first place, there's no way you can ever handle the exception in an action method.

Personally I would just do a try/catch, instantiate some error handling controller, and route the request through it instead.

A better question is - what are your controllers so dependent on that isn't being met that they have to throw exceptions when they're being constructed? Ostensibly, simply creating the controllers shouldn't be a huge source of exceptions. If they are, maybe you could look at lazily instantiating the dependencies in the action methods (rather than the constructor), and implementing an ErrorHandlingController approach. This would push the exceptions "down" into the controllers themselves, so you could take a more controller-centered approach to handling them.

womp
Thanks. I had some repository hook-up code in the constructor which was initializing a db connection. I'm now lazy loading it.
Jason