代码改变世界

让windows日志记录web程序的异常-EnterpriseLibrary.ExceptionHandling在asp.net mvc中的初步应用

2010-03-09 21:31  穆容  阅读(1594)  评论(0编辑  收藏  举报

实现的功能很简单,就是用企业库的异常处理模块和日志模块,利用windows的系统日志,记录web应用的异常。

我的企业库是4.1版

1.添加对Microsoft.Practices.EnterpriseLibrary.ExceptionHandling和Microsoft.Practices.EnterpriseLibrary.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
            { }
        }

3.在配置文件中加入

  <exceptionHandling>
    <exceptionPolicies>
      <add name="global expcetion"> //这就是你定义的异常名或者异常类型
        <exceptionTypes>
          <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="NotifyRethrow" name="Exception">
            <exceptionHandlers>
              <add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
                formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                name="Logging Handler" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
    </exceptionPolicies>
  </exceptionHandling>

4.在程序中加入下列代码测试异常

throw new Exception("Test");

5.注意:

需要将异常抛至全局处理的action,不要加异常过滤器IExceptionFilter,否则的话,异常无法传递到Application_Error。

如果一定要使用IExceptionFilter,则将ExceptionPolicy.HandleException(objErr, "global expcetion"); 加入至过滤器中即可