asp.net mvc 错误处理的最佳实践
我正在寻找一种标准方法来处理 asp.net mvc 2.0 或 3.0
- 404 错误处理程序
- 控制器范围异常错误处理程序
- 全局范围异常错误处理程序中的错误
I'm looking for a standard way to handle errors in asp.net mvc 2.0 or 3.0
- 404 error handler
- Controller scope exception error handler
- Global scope exception error handler
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于控制器范围错误,请尝试使用自定义异常属性,即
然后用该属性装饰控制器,并且错误处理应该由您负责。
如果错误与路由有关,则没有帮助 - 即它首先找不到控制器。为此,请尝试 Global.asax 中的应用程序错误处理程序,即
我不知道这是否是“最佳实践”。确实有效。
For controller scope errors try using a custom Exception attribute i.e.
Then decorate the controllers with the attribute and error handling should be yours
Doesn't help if the error is with the routing though - i.e. it can't find a controller in the first place. For that try the Application Error handler in Global.asax i.e.
I don't know if it's 'best practice' though. Does work.
不确定最佳实践,并且根据您想要对错误执行的操作,一个简单的解决方案不是使用 web.config 文件中的 customErrors 设置吗?
为了捕获未处理的错误,我有时会使用 Global.asax 文件中的 Application_Error 方法。
另外,看看这个SO帖子
Not sure about best practices and depending on what you want to do with the error, would a simple solution not be to use the customErrors setting in the web.config file?
For catching unhandled errors I sometimes make use of the Application_Error method in the Global.asax file.
Also, Take a look at this SO post
这里是最详细回答您问题的“404”部分。尽管主要主题是 404,但它会让您了解如何将其应用于其他错误类型。
尽管如此,我不能明确地将其表述为“最佳实践”,因为您需要使用这种方法的层超类型控制器。我最好在
Global.asax
中捕获那些HttpException
。但在大多数情况下,它是一个很好的指南。至于整个 MVC 应用程序中的任意异常 - 不要忘记
HandleErrorAttribute
。Here is the most detailed answer to "404" part of your question. Despite the main topic of that is 404 it would give you an idea about how to apply that to other error types.
Although, I can't state it clearly as the "best practice" since you'll need a layer supertype controller with that approach. I'd better catch those
HttpException
s inGlobal.asax
. But for the most part it is a great guide.As for arbitrary exceptions throughout your MVC-app - don't forget about
HandleErrorAttribute
.