处理在asp.net MVC控制器构造函数中发生的异常 [英] Handling Exceptions that happen in a asp.net MVC Controller Constructor

查看:450
本文介绍了处理在asp.net MVC控制器构造函数中发生的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制器的构造函数中处理异常的最好方法是什么?



我可以想到的是使用Application_OnError() catch在我的ControllerFactory。



这些解决方案都不是理想的。 Application_OnError是broad - 我有一些非mvc内容在网站有自己的错误处理。



使用try / catch块似乎有点黑客。 >

如果我提供不同的内容类型-html / text / json / rss ....我想能够处理action方法中的异常,而不是



我缺少这里的东西,还是有其他人来处理这个?

解决方案

如果在您的 ControllerFactory 中首次创建控制器时发生异常,在操作方法中没有办法处理异常。



我只是做一个try / catch,实例化一些错误处理控制器,



一个更好的问题是 - 你的控制器是什么依赖,这是不是被满足,他们必须抛出异常时,他们正在构建?表面上,简单地创建控制器不应该是一个巨大的异常来源。如果他们是,也许你可以看看懒惰实例化的动作方法(而不是构造函数)的依赖,并实现 ErrorHandlingController 方法。这将把异常推到控制器本身,所以你可以采取更加以控制器为中心的方法来处理它们。


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?

解决方案

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.

这篇关于处理在asp.net MVC控制器构造函数中发生的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆