上一篇说的是通过try{}catch{}的方法,基本是在方法内部的处理,但是,我们通常需要一个更加通用的、跟底层

的错误处理方法。于是,我们想到了下面几种方式!

1:自定义错误页面,在web.config 中配置,但系统有错误是,跳转到该页面,通常页面中提示“系统错误!重新登陆!”的信息。

     优点: 这种方式可以给用户提供友好的错误提示;配置简单;

     缺点:错误信息粒度过粗,不知道错误内容和类型;

     配置方法:

     Add the following code to the <customErrors> section to redirect the user to a custom page

     

<customErrors defaultRedirect="http://hostName/applicationName/errorStatus.htm" mode="On">
</customErrors>

 

2:通过基类来捕获异常

     大家都知道,Page页面的生命周期,我们可以重写page 中的 Page_Error  事件,来达到捕获异常的目的。

     代码如下:

     

public void Page_Error(object sender,EventArgs e)
{
    Exception objErr 
= Server.GetLastError().GetBaseException();
    
string err =    "<b>Error Caught in Page_Error event</b><hr><br>" + 
            
"<br><b>Error in: </b>" + Request.Url.ToString() +
            
"<br><b>Error Message: </b>" + objErr.Message.ToString()+
            
"<br><b>Stack Trace:</b><br>" + 
                      objErr.StackTrace.ToString();
    Response.Write(err.ToString());
    Server.ClearError();
}

     优点:通过这种方法,系统可以获取到任何异常,并且可以得到异常的详细信息!

     缺点:系统资源消耗大(相对),每个页面都需要继承基类。

 

3:Application_Error 处理异常

     这种处理异常的方式,可以吧异常信息写入系统的 错误日志

     

protected void Application_Error(object sender, EventArgs e)
{
    Exception objErr 
= Server.GetLastError().GetBaseException();
    
string err =    "Error Caught in Application_Error event\n" +
            
"Error in: " + Request.Url.ToString() +
            
"\nError Message:" + objErr.Message.ToString() + 
            
"\nStack Trace:" + objErr.StackTrace.ToString();
    EventLog.WriteEntry(
"Sample_WebApp",err,EventLogEntryType.Error);
    
//Server.ClearError();
    
//additional actions

 

4:自定义错误页面 与 详细错误信息共同处理的方式

     上面三种方式各有特点,我们可以选择适合自己的处理方式。我通常采用的是 自定义错误页面 与 详细错误信息共同处理的方式。

     在web.config中配置一个自定义的错误页面,并在这个页面显示详细错误信息,也可以在后台把这些错误信息写入日志或者数据库。

 

 

posted on 2008-09-09 10:31  杜辉  阅读(394)  评论(0编辑  收藏  举报