我有一个放在用户控件(ascx)上的自定义控件。在自定义控件的加载中发生错误。我想在用户控件(ascx)中“捕获”此错误。我怎么能这样做?
默认aspx:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebApplication1._Default" %>
<%@ Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body><form id="form1" runat="server">
<asp:Label runat="server" ID="test" Text="hello world"></asp:Label>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
</form></body></html>
WebUserControl1.ascx:
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="WebUserControl1.ascx.vb" Inherits="WebApplication1.WebUserControl1" %>
<%@ Register tagPrefix="test" namespace="WebApplication1" assembly="WebApplication1" %>
<test:MyControl runat="server" ID="test2" Text="test"></test:MyControl>
WebUserControl1.ascx.vb:
Public Class WebUserControl1
Inherits System.Web.UI.UserControl
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
Try
'Doesn't work!
MyBase.OnLoad(e)
Catch ex As Exception
handleException(ex)
End Try
End Sub
Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error
'Doesn't work!
handleException(New Exception())
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub handleException(ByVal ex As Exception)
Me.Controls.Add(New LiteralControl("ex.tostring"))
End Sub
End Class
最后但并非最不重要:我的自定义控件:
MyControl.vb:
Public Class MyControl
Inherits System.Web.UI.WebControls.Label
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
Throw New Exception("")
MyBase.OnLoad(e)
End Sub
End Class
我希望能够捕获此错误,在* .ascx文件中这似乎不可能?或者是吗?
答案 0 :(得分:0)
您无法拦截父控件中OnLoad
,OnInit
,OnPreRender
等事件中引发的异常。
您可以尝试通过附加到Page.Error
事件在Page / UserControl中执行此操作。
更好的选择是在global.asax
事件处理程序的Application_Error
文件中添加全局错误处理程序。