asp.net中 統一處理錯誤

來源:互聯網
上載者:User

轉載:

 

asp.net中當伺服器出錯時顯示指定的錯誤頁面同時把錯誤資訊寫入系統日誌文檔

 

一,在web.config中填寫出錯時顯示的頁面,能夠根據不同的statuscode顯示不同的出錯頁面。
   <customerrors mode="on"  //假如配置為off則出錯只返回錯誤資訊,不會跳到自己的指定頁面defaultredirect="/error/customerrorpage.aspx">
    <error statuscode="404" redirect="/error/404page.aspx"/>
    <error statuscode="403" redirect="/error/403page.aspx"/>
  </customerrors>

二,在global.asax文檔中添加應用出錯代碼,寫入系統日誌文檔
protected void application_error(object sender, eventargs e)
        {
            exception lasterror = server.getlasterror();
            string errmessage = lasterror.tostring();

            string logname  = "mylog";
            string message = "url " + request.path + " error: " + errmessage;

            // create event log if it doesnt exist
        
            if (!eventlog.sourceexists(logname))
            {
                eventlog.createeventsource(logname, logname);
            }
            eventlog log = new eventlog();
            log.source  = logname;
            //these are the five options that will display a different icon.
            log.writeentry(message, eventlogentrytype.information, 1);
            log.writeentry(message, eventlogentrytype.error, 2);
            log.writeentry(message, eventlogentrytype.warning, 3);
            log.writeentry(message, eventlogentrytype.successaudit, 4);
            log.writeentry(message, eventlogentrytype.failureaudit, 5);

        }
三,現在您能夠進行測試了。
我在default.aspx.cs中產生一個錯誤,果然跳到預設的錯誤頁面!
private void page_load(object sender, system.eventargs e)
        {
            // put user code to initialize the page here
            try
            {
                int y=0;
                int x=1/y;
            }
            catch (exception err)
            {
                throw new exception("404");//我想產生不同的錯誤,對應web.config中的statuscode,該如何??
                //err.
            }

同理:如果要在所有入口處判斷SESSION是否到期,例如登入資訊,也可以通過 application的全域實踐來進行監控

Application事件的執行順序-.NET教程,Asp.Net研發

執行application_beginrequest
執行application_authenticaterequest
執行application_authorizerequest
執行application_resolverequestcache
執行application_acquirerequeststate
執行application_prerequesthandlerexecute
執行application_postrequesthandlerexecute
執行application_releaserequeststate
執行application_updaterequestcache
執行application_endrequest

 

類似與JAVA中的攔截器Filter,見前期的文章【使用filter攔截器判斷會話是否丟失】

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.