11.在Global的Application_Error處理錯誤示例


Application_Error是在程序出問題時觸發的事件。

這里面要用到錯誤頁的情況,所以要配置web.config的customError項。

1.建立Global文件,在它的Application_Error中寫入以下代碼(TextFile1.txt 是要記錄出錯信息的日志):

 protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = HttpContext.Current.Server.GetLastError();
            File.WriteAllText(HttpContext.Current.Server.MapPath("~/TextFile1.txt"), ex.Message + DateTime.Now.ToShortTimeString());
        }

2.建立兩個錯誤頁,一個為默認的錯誤頁,另一個為404狀態的錯誤頁,即頁面沒有被找到,

   默認錯誤頁error.htm

  

<!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>
    <title></title>
</head>
<body>
出錯啦
</body>
</html>

 找不到文件錯誤頁NotFoundFile.htm

<!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> <title></title> </head> <body> 沒找到相關文件 </body> </html>

3.設置web.config,具體說明可以看錯誤頁章節

  

<?xml version="1.0" encoding="utf-8"?>

<!--
  有關如何配置 ASP.NET 應用程序的詳細消息,請訪問
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
      <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="error.htm">
        <error statusCode="404" redirect="NotFoundFile.htm"/>
      </customErrors>
    </system.web>

</configuration>

4.建立一個webform面,在它的page_load事件中寫如下cs代碼:

 protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("IP:127.0.0.1;datasource=db1.db");
            conn.Open();
        }

此時運行時就會顯示錯誤頁,打開TextFile1.txt后會出現日志已記錄在文件中,如下圖日志記錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM