Handling Exceptions that happen in a asp.net MVC Controller Constructor

倾然丶 夕夏残阳落幕 提交于 2019-12-22 06:23:32

问题


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:


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.



来源:https://stackoverflow.com/questions/2694849/handling-exceptions-that-happen-in-a-asp-net-mvc-controller-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!