惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
雷峰网
雷峰网
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Spread Privacy
Spread Privacy
H
Hacker News: Front Page
PCI Perspectives
PCI Perspectives
Webroot Blog
Webroot Blog
罗磊的独立博客
H
Heimdal Security Blog
TaoSecurity Blog
TaoSecurity Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
Last Week in AI
Last Week in AI
美团技术团队
Help Net Security
Help Net Security
The Hacker News
The Hacker News
C
Cisco Blogs
T
The Blog of Author Tim Ferriss
J
Java Code Geeks
The Register - Security
The Register - Security
IT之家
IT之家
WordPress大学
WordPress大学
Jina AI
Jina AI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Help Net Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threat Research - Cisco Blogs
P
Proofpoint News Feed
NISL@THU
NISL@THU
爱范儿
爱范儿
The GitHub Blog
The GitHub Blog
Scott Helme
Scott Helme
V
Vulnerabilities – Threatpost
B
Blog
T
Tenable Blog
博客园 - 三生石上(FineUI控件)
T
The Exploit Database - CXSecurity.com
S
Security Affairs
小众软件
小众软件
Hacker News: Ask HN
Hacker News: Ask HN
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
W
WeLiveSecurity
A
Arctic Wolf
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence

博客园 - Valens

IIS无法启动:存储空间不足解决办法 做程序员的,平时眼睛总对着代码,很累!看看美女放松放松哦! - Valens - 博客园 How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA Mark:使用线程处理(C# 编程指南) 交集:通过使用默认的相等比较器对值进行比较生成两个序列的交集 LINQ to SQL StepByStep (1) 就事网上线了 About .net Format 【技巧】asp的找不到文件的问题 【翻译】父窗口关闭的时候子窗口也同时关闭 - Valens - 博客园 【翻译】Visual Studio Smart Tag Expansion 小技巧 ListView提示和技巧 独有数据绑定控件ListView LINQ的标准查询操作符 轻松Web调试、扩展Reflector及更多内容 构建不带Web窗体的Web应用程序_ASP.NET MVC ASP.NET 应用程序的扩展策略 单页界面和AJAX模式 删除Visual Studio IDE最近打开文件和项目列表
【翻译】使用ASP.NET 2.0记录错误
Valens · 2008-06-18 · via 博客园 - Valens

Valens
原文:http://www.dotnetcurry.com/ShowArticle.aspx?ID=94&AspxAutoDetectCookieSupport=1
使用ASP.NET 2.0记录错误

在我们开发和操作一个网站的过程中不可避免会发生错误和失败的情况. ASP.NET 2.0 提供了跟踪,instrumentation以及错误处理机制来检测和修补程序中的问题.

在本文中,我们将通过一个简单的处理来记录在我们的网站中的错误和异常.我们会这样操作:每当遇到程序错误时,将使用者导航到一个单独的页面.同时,错误将被记录到服务器上的一个文本文件.每当错误发生时,我们将以日志的形式每天记录.说了这么多,让我们来看一些代码.

步骤一:首先创建一个错误文件夹用于存放错误日志文件.鼠标右键站点 > 创建新文件夹.将该文件夹命名为"Error". 如果站点中没有 Web.config 文件时,请添加一个. 右键站点 > 添加新项目 > Web.config.

步骤二:现在我们要创建一个错误处理的代码.我们只需要右键站点 > 添加新项目 > 选择类. 重命名该类为"ErrHandler.cs" ,然后单击 "添加" 按钮.当你这么操作的时候,会弹出一个对话框,是否要将这个类文件保存在"App_Code"里面,我们选择接受.

步骤三:现在我们为ErrHandler.class添加一些功能.该类用于接受错误信息并将错误信息保存在一个文本文件中.每天创建一个这样的文本文件.如果已经存在相同的文件名时,错误信息将会追加到这个文件中.否则,就创建一个新文件,并将错误信息写入该文件.

代码看来如下:

    /// Handles error by accepting the error message 
    
/// Displays the page on which the error occured
    public static void WriteError(string errorMessage)
    {
        
try
        {
            
string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy"+ ".txt";
            
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
            }
            
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                w.WriteLine(
"\r\nLog Entry : ");
                w.WriteLine(
"{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                
string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                              
". Error Message:" + errorMessage;
                w.WriteLine(err);
                w.WriteLine(
"__________________________");
                w.Flush();
                w.Close();
            }
        }
        
catch (Exception ex)
        {
            WriteError(ex.Message);
        }
    }

这就是我们的ErrHandler类了.然后我们来看看如何使用这个类和在Page级中(Application级中)处理错误.

在Page级中处理错误

在Default.aspx中,从工具箱中添加一个button控件.将这个button命名为 btnError 并设置值为 "Throw Handled Exception".我们将抛出一个异常.只要我们定义了 catch 块,当错误发生时,就会被捕捉到并登记在Error文件夹中.文本文件将以当天的日期作为文件名,不存在文件时,一个新的文件将会被以下代码所创建.

按钮点击操作代码如下:

protected void btnHandled_Click(object sender, EventArgs e)
    {
        
try
        {
            
throw new Exception("Sample Exception");
        }
        
catch (Exception ex)
        {
            
// Log the error to a text file in the Error folder
            ErrHandler.WriteError(ex.Message);
        }
    }

现在,运行程序,并点击按钮.因为我们已经在代码中处理了错误和记录下了异常,你会发现当点击按钮时,似乎什么也没发生.关闭程序,刷新Error文件夹,你会看到有个以今天日期为文件名的新文件被创建.异常已经被成功记录下如下所示.其中日期和时间在您的机器上会有所不同.

Log Entry :
01/11/2008 23:33:46
Error in: http://localhost:51087/ErrorHandling/Default.aspx. Error Message:Sample Exception
__________________________

Redirecting users on unhandled errors(在未有处理错误情况下重定向用户)

让我们看看如何在Application级上来捕捉未有错误处理而发生的错误,并将用户定向到一个不同的页面.

要捕捉到未有错误处理的错误,只需做以下的工作即可.添加一个 Global.asax 文件(右键工程项目 > Add New Item > Glabal.asax).在当中的 Application_Error() 方法中,增加以下代码:

 void Application_Error(object sender, EventArgs e)
    {
        
// Code that runs when an unhandled error occurs
        Exception objErr = Server.GetLastError().GetBaseException();
        
string err = "Error in: " + Request.Url.ToString() +
                          
". Error Message:" + objErr.Message.ToString();
        
// Log the error
        ErrHandler.WriteError(err);        
    }

我们注意到通过使用 Server.GetLastError() 函数来捕捉错误.当一个未有错误处理的错误发生时,要将用户重定向到不同的页面,我们要做的是,打开你的 Web.config 文件,并定位到 <customErrors> 标签处并注销它.在移除注释后,标签看来应该是这样的:

<!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.        
-->
 
                  
<customErrorsmode="RemoteOnly"defaultRedirect="GenericErrorPage.htm">
                        
<errorstatusCode="403"redirect="NoAccess.htm" />
                        
<errorstatusCode="404"redirect="FileNotFound.htm" />
                  
</customErrors>

将:
 mode="RemoteOnly"tomode="On"
defaultRedirect="GenericErrorPage.htm" to defaultRedirect="ErrorPage.aspx"
修改为:

<customErrorsmode="On"defaultRedirect="ErrorPage.aspx">
                        
<errorstatusCode="403"redirect="NoAccess.htm" />
                        
<errorstatusCode="404"redirect="FileNotFound.htm" />
                  
</customErrors>

这个配置文件将会将用户导向 名为ErrorPage.aspx 的页面.我们来创建这个错误页面,并显示一些信息给用户.

右键网站 > Add New Item > 创建 ErrorPage.aspx ,然后显示一个信息在页面中,提示用户有个错误发生了.

为了测试这个功能,我们回到 Default.aspx, 添加新的按钮并命名为 btnUnhandled 并将文本属性设置为 Throw Unhandled Exception.我们将使用"Divide By Zero"异常.并不去处理它.我们可以发现少了 catch 块.所以当错误发生时,用户就会按照我们在web.confg文件中设置的重定向到 "ErrorPage.aspx".

protected void btnHandled_Click(object sender, EventArgs e)
{
      
int i = 9;
      
int j = 0;
      Respone.Write( i 
/ j );
}

运行这个程序点击 "Throw Unhandled Exception" 按钮.你会发现用户被自动地定向到了 Error 页面.并且错误也被记录在 Error 文件夹中.

 源码下载