2

我正在使用 Visual Studio 2005 和 .NET 2.0 在 Visual Basic 中编写一个 Web 应用程序。我背后的代码(Default.aspx.vb)看起来像这样。

Partial Public Class frmDefault
    Inherits System.Web.UI.Page

    Protected PageData As New Dictionary(Of String, String)

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        PageData("text") = "Hello World!"
    End Sub
End Class

在 Default.aspx 中,我有

<%=PageData("text")%>

当放在实时服务器上时(每天将获得大约 40 次唯一点击),这将导致零星的“字典中不存在给定的键”。以下堆栈跟踪错误:

at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at ASP.default_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.Control.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
at ASP.forms_glass_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.Control.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.Page.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

我每天会在日志中看到 1-2 次,但我自己在调试、测试或使用实时应用程序时从未遇到过错误。

为了记录更多信息,我尝试通过将其放入表单类中来捕获关键错误:

Protected Function GetPageData(ByRef Key As String) As String
    Try
        Return PageData(Key)
    Catch Ex As Exception
        'Log the exception
    End Try
End Function

并在 Default.aspx 中使用它:

<%=GetPageData("text")%>

自从我发布此更改(一个多月前)以来,我还没有记录任何关键异常。

(1) 什么可能导致原始代码产生关键异常?

(2)为什么更新后的代码没有产生类似的key异常?

4

0 回答 0