elmah_ELMAH和异常驱动开发FTW

博客作者分享了如何通过ELMAH工具在NerdDinner应用中发现并解决一个NullReference异常。他强调了日志和工具在调试中的重要性,通过改进代码来避免假设UserAgent总是存在的问题。这个经验教训提醒开发者要验证他们的假设,并且在编程时考虑异常情况。
摘要由CSDN通过智能技术生成
elmah

elmah

Jeff blogged last month about Exception-Driven Development. I've been using ELMAH for years and you should too. Having great instrumentation in your app is such a joy. I added ELMAH to NerdDinner and have learned all sorts of things. It's amazing that someone would care to hack a site about Nerds eating dinner, but they try.

Jeff在上个月写了关于Exception-Driven Development的博客。 我已经使用ELMAH多年了,您也应该使用ELMAH 。 在您的应用程序中拥有出色的工具实在是一件乐事。 我将ELMAH添加到NerdDinner并学到了各种各样的东西。 令人惊讶的是,有人愿意入侵有关Nerds吃晚饭的网站,但他们尝试了。

This wasn't a hack, but a great bug found in my Nerd Dinner Mobile code that I wouldn't have thought to look for. Here I'm getting a NullReference Exception...why?

这不是黑客,而是我不想想到的在Nerd Dinner Mobile代码中发现的一个很大的错误。 在这里,我得到一个NullReference异常...为什么?

Well, here's the code:

好吧,这是代码:

private bool UserAgentIs(ControllerContext controllerContext, string userAgentToTest)
{
return (controllerContext.HttpContext.Request.UserAgent.IndexOf(userAgentToTest,
StringComparison.OrdinalIgnoreCase) > 0);
}

Of course, I'm breaking the " Law Suggestion of Demeter" with all that digging, but what's the real issue? I'm assuming that the request has a UserAgent string at all! Exactly as the YSOD that ELMAH "tivo'ed" for me above.

当然,我在挖掘所有内容时都违反了《 Demeter 法律 建议》,但是真正的问题是什么? 我假设该请求完全具有UserAgent字符串! 就像上面ELMAH为我“推销”的YSOD一样。

So I changed it to this. Yes, I know that this could all be on one line and really baroque, but I find a few more lines to be easier to read.

因此,我将其更改为此。 是的,我知道这可能全都在一行上,而且确实是巴洛克式,但是我发现还有几行更容易阅读。

public bool UserAgentIs(ControllerContext controllerContext, string userAgentToTest)
{
string UA = controllerContext.HttpContext.Request.UserAgent;
if (string.IsNullOrEmpty(UA) == true)
return false;
return (UA.IndexOf(userAgentToTest, StringComparison.OrdinalIgnoreCase) > 0);
}

I likely would have never thought of this bug had I not had logs and instrumentation. A smart user could have told me, or I could have used a Unit Test Generator like Pex, OR I could have just used my head and thought of it first. ;) Assert your assumptions. I didn't, and I assumed, wrongy, UserAgent would be non-null.

如果没有日志和工具,我可能永远也不会想到这个错误。 精明的用户可能会告诉我,或者我可能使用了Pex之类的单元测试生成器,或者我可能只是首先想到了它。 ;)提出您的假设。 我没有,我以为是错误的,UserAgent不会为空。

翻译自: https://www.hanselman.com/blog/elmah-and-exception-driven-development-ftw

elmah

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值