从用户控件中的 Page 捕获异常

本文关键字:Page 捕获异常 用户 控件 | 更新日期: 2023-09-27 17:56:10

用户控件是否可以捕获其父页的 Page.Error 事件并记录该异常?

从用户控件中的 Page 捕获异常

您可以这样做,但这不是最好的解决方案,它仅在事件注册后发生错误时才有效,这意味着在控件加载之后,由于页面首先加载,它不会在页面加载中捕获任何错误。 更好的解决方案是在global.asax中使用Application_Error事件。

将此代码置于您的控件中:

protected void Page_Load(object sender, EventArgs e)
{
    Page.Error += new EventHandler(Page_Error);
}
void Page_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Response.Write(exception.ToString());
    HttpContext.Current.ClearError();
}