在ASP.NET MVC2中正确的错误处理 [英] Proper error handling in ASP.NET MVC2

查看:221
本文介绍了在ASP.NET MVC2中正确的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的基本控制器中覆盖了OnException(ExceptionContext filterContext),以便在任何错误期间捕获应用程序,然后记录它们。我在应用程序中遇到的问题是这个特定的方法是针对某些错误被四次触发。我会引导您完成一个场景:



让我们来看看:
http:// localhost:180 / someController / someAction?someId = XX



而且我差我的代码中的对象处理。传入的Id是一个无效的,它检索一些空对象,然后我的坏对象处理的bc,尝试对空对象进行操作。我收到一个例外。



BaseController的OnException在这里被触发。



空对象仍然返回视图,视图试图将它绑定到某个东西,或者你有什么。



BaseController的OnException在这里再次被触发,因为视图中的错误。 p>

基本上,只有一个错误对我很重要,但是涓流效应导致更多错误被触发,垃圾邮件发送到我的收件箱: - /。



在MVC2中捕获错误的正确方法是什么?没有发生这种情况?

解决方案

我建议你继承HandleError属性并滚动你的异常处理。在单个控制器上覆盖OnException意味着您在许多控制器中有很多异常处理代码,或者从基础控制器继承,因为MVC管道在这两种情况下都不是必需的。



通过使用该属性,您应该每次执行一个操作都会发生一个错误,一旦处理错误,它将不会再次触发。希望这将减少重复的异常消息。



我个人使用异常处理的属性,因为它更干净,更可重用,并在我的操作中摆脱了很多噪音。


I have an override OnException(ExceptionContext filterContext) in my base controller to catch the app during any errors, and then log them. The problem I'm getting in my app is this particular method is fired off four times for certain errors. I'll walk you through a scenario:

Let's say i navigate to: http://localhost:180/someController/someAction?someId=XX

And I have poor object handling in my code. The Id passed in is an invalid one, and it retrieves some null object, I then, bc of my bad object handling, try to operate on a null object. I get an exception.

BaseController's OnException is fired off here.

That null object is still returned out to the view, where the view tries to bind it to something, or what have you.

BaseController's OnException is fired off here again, for the error in the view.

Essentially, only one error is important to me, but the trickle up effect is causing more errors to fire off, and spam my inbox :-/.

What is the correct way to catch an error in MVC2 and not have this happen to me?

解决方案

I would recommend you inheriting from the HandleError attribute and rolling your exception handling in there. Overriding the OnException on a single controller means you either have a lot of exception handling code in a lot of controllers or your inherit from a base one, which due to the MVC pipeline is not really necessary in either case.

By using the attribute, you should have one occurrence of an error per action executed, and once the error is handled it won't fire again. Hopefully this will cut down on repeat exception messages.

I personally use attributes for the exception handling cause it's cleaner and more reusable and get's rid of a lot of noise within my actions.

这篇关于在ASP.NET MVC2中正确的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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