2012-07-12 34 views
2

我们在C#中使用asp.net。我有页面(.aspx)由多个网页用户控件(.ascx)组成ASP .Net用户控制错误处理

我想有一个错误处理机制的方式,如果在用户控件之一有任何异常,asp .net应该在控件上显示一些友好的错误消息。所有其他控件应按预期呈现。

如果没有在您显示/隐藏的每个控件上放置占位符,并且在发生异常的情况下,是否可以执行此操作?

+1

何时会发生异常?我会尝试让每个用户控件在内部处理,而不是全局处理。 – Matthew 2012-07-12 19:46:22

+0

通常会在用户控件中发生异常(例如,某些数据库连接错误,类型转换错误等)。 – Neil 2012-07-12 19:49:02

+1

然后,您应该将数据库调用和投射操作包装在try/catch中,所有这些都应该在用户控件中完成。当我编程时,我倾向于只捕捉可能处理的异常,而我只是让应用程序失败的关键事情。 – Matthew 2012-07-12 19:54:37

回答

3

你可以做这样的事情。

一个抽象基类,带有每个UserControl必须实现的抽象OnLoad()。您可以对任何想要共享错误处理的事件使用相同的模型。

public abstract class BaseUserControl : UserControl 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     try 
     { 
      OnLoad(); 
     } 
     catch (Exception) 
     { 
      //Custom error handling here 
     } 
    } 

    protected abstract void OnLoad(); 
} 

public class MyUserControl: BaseUserControl 
{ 
    protected override void OnLoad() 
    { 
     //My normal load event handling here 
    } 
} 
+0

这适用于普通事件,但是点击事件和控件引发的其他事件呢? – Slight 2017-01-03 21:54:32

1

1)在App_Code文件,创建一个类MyPage.cs继承页

class MyPage : Page { } 

2)改变你的页面继承来我的页面。

public partial class _Default : MyPage { ... 

有在web.config属性可以用来改变它,如果你想

3)回到MyPage.cs,添加所有页面的一般错误处理程序

protected override void OnError(EventArgs e) 
{ 
    /* here you can intercept the error and show the controls that you want */ 
    base.OnError(e); 
} 
+0

感谢您的回答。我们正在使用Content Management System调用Sitecore。我有一个页面和控件(.ascx)是动态添加的。 – Neil 2012-07-12 20:48:14

-1

首先创建一个覆盖默认的onerror事件的基本用户控件类。

public class MyControlClass:UserControl 
     { 

      protected override void OnError(EventArgs e) 
      { 
       //here you sould add your friendly msg implementation 



       //base.OnError(e); here should remain commented 
      } 
     } 

然后你就可以创建用户控件:

public class Control1:MyControlClass 
    { 
     // .... 
     // .... 
    } 

因此,如果任何控件创建一个例外,其余部分将继续工作。

+1

感谢您的回复。但它不会工作,因为控制永远不会引发OnError(),请看博客:http://weblogs.asp.net/vga/archive/2003/06/16/8748.aspx – Neil 2012-07-13 14:04:28