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

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

问题描述

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

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

所有我能想到的做的是使用Application_OnError()或者把一个try / catch在我的ControllerFactory。

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

这些解决方案都似乎理想。 Application_OnError是广 - 我在,有它自己的错误处理现场一些非MVC含量

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.

使用try / catch块似乎有点哈克。

Using a try/catch block seems kinda hacky.

如果我提供不同的内容类型-html /文本/ JSON / RSS ....我希望能够从操作方法中处理,而不必写各种条件,以确定哪些异常一种错误信息的服务。

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?

推荐答案

如果一个例外是发生在的ControllerFactory 创建摆在首位控制器的时候,有没有办法你所能处理异常的操作方法。

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.

我个人只是做一个try / catch,实例化一些错误处理控制器,并且将请求路由通过它来代替。

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

一个更好的问题是 - 什么是你的控制器,以便依赖于没有被满足,他们有正在被建造时,他们抛出的异常?从表面上看,简单地创建控制器不应该是一个巨大的例外的来源。如果是这样,也许你可以看一下实例懒洋洋地依赖于动作方法(而非构造函数),和实施<一个href=\"http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx\"><$c$c>ErrorHandlingController接近。这将推动例外倒入控制器本身,所以你可以采取更为控制器为中心的方法来处理它们。

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天全站免登陆