我如何赶上我的ASCX控件引发的异常(不是code-后面)? [英] How do I catch an exception raised on my ASCX control (not the code-behind)?

查看:148
本文介绍了我如何赶上我的ASCX控件引发的异常(不是code-后面)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多ASCX控制大型ASPX页面。如果控制抛出一个异常,就应该记录异常,而且只隐藏。所有其他控件还是应该渲染。

I have a large ASPX page with many ASCX controls. If a control throws an exception, it should log the exception and hide only itself. All the other controls should still render.

我如何处理来自前端文件(ASCX而不是code-后面)上调个人ASCX的异常?例如:控制尝试使用引用无效的财产<%= MethodThatThrowsANullReferenceException()%GT; 语法

How do I handle exceptions on individual ASCX's raised from the front-end file (the ASCX and not the code-behind)? for example: a control trying to reference an invalid property using the <%= MethodThatThrowsANullReferenceException() %> syntax.

显然使用在Global.asax中的一般错误处理方法并不能解决问题。我需要处理个人控制的异常。

Obviously using the generic error handler method in Global.asax won't solve the problem. I need to handle exceptions on individual controls.

推荐答案

一个选项,由吉姆·波拉建议是让所有的控制从同一个基类继承,并在Render方法使用一个try / catch。这会工作。不幸的是许多我处理已经控制有不同的基类。

One option, as suggested by Jim Bolla was to make all controls inherit from the same base class and use a Try/Catch in the Render method. This would have worked. Unfortunately many of the controls I am dealing with already have different base classes.

该解决方案为我工作:

我添加了以下code到每个用户控件(我敢肯定,这可以进一步重构,以减少重复):

I added the following code to each user control (I'm sure this can be refactored further to reduce duplication):

#region Error Handling

public event EventHandler ControlCrashed;
private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

protected override void RenderChildren(HtmlTextWriter writer)
{
    try
    {
        base.RenderChildren(writer);
    }
    catch (Exception exc)
    {
        Logger.Error("Control failed to load. Hiding control. Message: " + exc, exc);
        //Ignore and hide the control.
        this.Visible = false;
        if (ControlCrashed != null)
            ControlCrashed(this, EventArgs.Empty);
    }
}

#endregion

这捕获任何前端渲染的问题。如果它希望展示一个漂亮的错误消息父页面可以处理ControlCrashed事件。

This catches any front-end rendering problems. The parent page can handle the ControlCrashed event if it wishes to display a nice error message.

这篇关于我如何赶上我的ASCX控件引发的异常(不是code-后面)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆