使用 Elmah 记录 MVC3 中的逻辑和数据错误
我的 MVC3 应用程序中有一个服务层,它充当存储库的角色,作为我的数据层和实际 Web 应用程序之间的层。我已使用 FirstOrDefault 而不仅仅是 First 对所有 GetById
方法进行了鲁棒性编码,因为 Id 是在 URL 中传递的,并且不能保证是有效的 Id。
我现在发现自己正在执行 FirstOrDefault
,然后仅在结果不为空时才继续。我想在事件为空时记录该事件,然后继续不执行任何操作等。现在,我已经使用 Elmah 来记录未处理的异常,并且我在 MVC3 中对异常处理等方面的经验很少,但它发生了我认为使用简单的 First
可能会更好,如果没有找到实体,Elmah 会记录异常。
我应该如何处理这种情况,其中无效 Id 绝对是逻辑异常,而不是低级 CLR 异常?这与当某人被要求输入 ID 而没有找到其搜索词的实体时不同,这是正常的逻辑结果。
I have a Service layer in my MVC3 app, which plays the role of a Repository among other things, as a layer between my Data layer and the actual web application. I have coded all my GetById
methods to be robust, using FirstOrDefault
and not just First, because the Id is passed in a URL and cannot be guaranteed to be a valid Id.
I now find myself where I'm doing a FirstOrDefault
, then only proceeding if the result is not null. I would like to log the event when it is null, and then proceed to do nothing etc. Now, I am already using Elmah to log unhandled exceptions, and I have very little experience with exception handling etc. in MVC3, but it occurs to me that it might be better for me to use a simple First
, with Elmah logging the exception if no entity is found.
How should I approach this scenario, where an invalid Id is quite definitely an logic exception, but not a low level CLR exception? This is not like when somebody is asked to enter an Id and no entity is found for their search term, which is a normal logic result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
生成异常的成本可能很高。您验证用户输入的初始方法更加可靠。我建议使用 NLog (http://nlog-project.org) 等日志框架来记录传入无效 ID 的情况。
如果您想将所有日志消息保留在 Elmah 中,那么您可以决定直接写入 Elmah 的错误日志而不是冒泡异常。
Generating exceptions can be expensive. You're initial approach of validating user input is more robust. I would recommend using a logging framework such as NLog (http://nlog-project.org) to log the case were an invalid ID is passed in.
If you would like to keep all of your log messages in Elmah, then you can decide to write directly to Elmah's error log instead of bubbling-up an exception.