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.
开发者_JAVA技巧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?
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.
精彩评论