首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

Enterprise Library Exception Handling 在 ASP.NET MVC 初步應用

     編輯:關於ASP.NET

目標

使用 EntLib 4.1 異常處理區塊 + 日誌區塊,將 Web 異常寫入 Windows 事件日誌。

步驟

  1. 加入參考:Microsoft.Practices.EnterpriseLibrary.ExceptionHandling、.Logging
  2. 重寫 Application_Error:
protected void Application_Error(Object sender, EventArgs e)
{
    try {
        Exception objErr = Server.GetLastError().GetBaseException();
        Application["errorPage"] = Request.Url.ToString();
        Application["errorMsg"] = objErr.Message;
        Server.ClearError();
        ExceptionPolicy.HandleException(objErr, "global expcetion");
    } catch {}
}
  1. web.config 設定異常策略:
<exceptionHandling>
  <exceptionPolicies>
    <add name="global expcetion">
      <exceptionTypes>
        <add type="System.Exception, mscorlib..." postHandlingAction="NotifyRethrow" name="Exception">
          <exceptionHandlers>
            <add logCategory="General" eventId="100" severity="Error" 
                 title="Enterprise Library Exception Handling"
                 formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter..."
                 priority="0" useDefaultLogger="false"
                 type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler..."
                 name="Logging Handler" />
          </exceptionHandlers>
        </add>
      </exceptionTypes>
    </add>
  </exceptionPolicies>
</exceptionHandling>
  1. 測試:throw new Exception("Test");

注意

  • 不可加 IExceptionFilter 否則異常不會傳至 Application_Error;若必須用 Filter,請在 Filter 內呼叫 ExceptionPolicy.HandleException。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved