Asp.net的NamePipe机制给我们提供了很多扩展性. 使用HttpModule我们可能实现的有:
下面我们来看如何实现自定义异常处理:
1 |
<span class="lnum"> 1: </span> <span class="kwrd">public</span> <span class="kwrd">class</span> ErrorModule:IHttpModule |
1 |
<span class="lnum"> 2: </span> { |
1 |
<span class="lnum"> 3: </span> <span class="preproc">#region</span> IHttpModule Members |
1 |
<span class="lnum"> 4: </span> |
1 |
<span class="lnum"> 5: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 6: </span> <span class="rem">/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.</span> |
1 |
<span class="lnum"> 7: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 8: </span> <span class="kwrd">public</span> <span class="kwrd">void</span> Dispose() |
1 |
<span class="lnum"> 9: </span> { |
1 |
<span class="lnum"> 10: </span> <span class="rem">//do nothing </span> |
1 |
<span class="lnum"> 11: </span> } |
1 |
<span class="lnum"> 12: </span> |
1 |
<span class="lnum"> 13: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 14: </span> <span class="rem">/// Initializes a module and prepares it to handle requests.</span> |
1 |
<span class="lnum"> 15: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 16: </span> <span class="rem">/// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param></span> |
1 |
<span class="lnum"> 17: </span> <span class="kwrd">public</span> <span class="kwrd">void</span> Init(HttpApplication context) |
1 |
<span class="lnum"> 18: </span> { |
1 |
<span class="lnum"> 19: </span> context.Error += <span class="kwrd">new</span> EventHandler(customcontext_Error); |
1 |
<span class="lnum"> 20: </span> } |
1 |
<span class="lnum"> 21: </span> |
1 |
<span class="lnum"> 22: </span> <span class="kwrd">private</span> <span class="kwrd">void</span> customcontext_Error(<span class="kwrd">object</span> sender, EventArgs e) |
1 |
<span class="lnum"> 23: </span> { |
1 |
<span class="lnum"> 24: </span> HttpContext ctx = HttpContext.Current; |
1 |
<span class="lnum"> 25: </span> HttpResponse response = ctx.Response; |
1 |
<span class="lnum"> 26: </span> HttpRequest request = ctx.Request; |
1 |
<span class="lnum"> 27: </span> |
1 |
<span class="lnum"> 28: </span> Exception exception = ctx.Server.GetLastError(); |
1 |
<span class="lnum"> 29: </span> |
1 |
<span class="lnum"> 30: </span> var sboutput = <span class="kwrd">new</span> StringBuilder(); |
1 |
<span class="lnum"> 31: </span> sboutput.Append(<span class="str">"Querystring:<p/>"</span>); |
1 |
<span class="lnum"> 32: </span> <span class="rem">//Get out the query string </span> |
1 |
<span class="lnum"> 33: </span> <span class="kwrd">int</span> count = request.QueryString.Count; |
1 |
<span class="lnum"> 34: </span> <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i < count; i++) |
1 |
<span class="lnum"> 35: </span> { |
1 |
<span class="lnum"> 36: </span> sboutput.AppendFormat(<span class="str">"<br/> {0}:-- {1} "</span>, request.QueryString.Keys[i], request.QueryString[i]); |
1 |
<span class="lnum"> 37: </span> } |
1 |
<span class="lnum"> 38: </span> <span class="rem">//Get out the form collection info</span> |
1 |
<span class="lnum"> 39: </span> sboutput.Append(<span class="str">"<p>-------------------------<p/>Form:<p/>"</span>); |
1 |
<span class="lnum"> 40: </span> count = request.Form.Count; |
1 |
<span class="lnum"> 41: </span> <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i < count; i++) |
1 |
<span class="lnum"> 42: </span> { |
1 |
<span class="lnum"> 43: </span> sboutput.AppendFormat(<span class="str">"<br/> {0}:-- {1} -- <br/>"</span>, request.Form.Keys[i], request.Form[i]); |
1 |
<span class="lnum"> 44: </span> } |
1 |
<span class="lnum"> 45: </span> sboutput.Append(<span class="str">"<p>-------------------------<p/>ErrorInfo:<p/>"</span>); |
1 |
<span class="lnum"> 46: </span> sboutput.AppendFormat(<span class="str">@"Your request could not processed. Please press the back button on your browser and try again.<br/></span> |
1 |
<span class="lnum"> 47: </span> If the problem persists, please contact technical support<p/> |
1 |
<span class="lnum"> 48: </span> Information below is for technical support:<p/> |
1 |
<span class="lnum"> 49: </span> <p/>URL:{0}<p/>Stacktrace:---<br/>{1}<p/>InnerException:<br/>{2}" |
1 |
<span class="lnum"> 50: </span> , ctx.Request.Url, exception.InnerException.StackTrace, exception.InnerException); |
1 |
<span class="lnum"> 51: </span> |
1 |
<span class="lnum"> 52: </span> response.Write(sboutput.ToString()); |
1 |
<span class="lnum"> 53: </span> |
1 |
<span class="lnum"> 54: </span> <span class="rem">// To let the page finish running we clear the error</span> |
1 |
<span class="lnum"> 55: </span> ctx.Server.ClearError(); |
1 |
<span class="lnum"> 56: </span> } |
1 |
<span class="lnum"> 57: </span> |
1 |
<span class="lnum"> 58: </span> <span class="preproc">#endregion</span> |
1 |
<span class="lnum"> 59: </span> |
1 |
<span class="lnum"> 60: </span> } |
上面的代码实现了IHttpModule接口, 实现基于HttpApplication.Error事件, 接着我们自定义输出了一些信息,包括Form,QueryString. 最后把原来的Error信息清除了,这样你看到以前那个黄页了. 这个自定义的Module可以用于调试Web应用程序使用.
Web.config中配置:
1 |
<span class="kwrd"><</span><span class="html">httpModules</span><span class="kwrd">></span> |
1 |
<span class="kwrd"><</span><span class="html">add</span> <span class="attr">name</span><span class="kwrd">="ErrorLoggingModule"</span> <span class="attr">type</span><span class="kwrd">="MyWeb.ErrorModule"</span><span class="kwrd">/></span> |
1 |
<span class="kwrd"></</span><span class="html">httpModules</span><span class="kwrd">></span> |
实际开发中,我们可以做的事儿很多,对这些信息记日志,发邮件. 如下, 我们演示使用Enterprise Library 做异常处理并日志记录,部分代码如下:
1 |
<span class="lnum"> 1: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 2: </span> <span class="rem">/// Handles the Error event of the EntLibLogging control.</span> |
1 |
<span class="lnum"> 3: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 4: </span> <span class="rem">/// <param name="sender">The source of the event.</param></span> |
1 |
<span class="lnum"> 5: </span> <span class="rem">/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param></span> |
1 |
<span class="lnum"> 6: </span> <span class="rem">/// <remarks>author Petter Liu http://wintersun.cnblogs.com</remarks></span> |
1 |
<span class="lnum"> 7: </span> <span class="kwrd">private</span> <span class="kwrd">void</span> EntLibLogging_Error(<span class="kwrd">object</span> sender, EventArgs e) |
1 |
<span class="lnum"> 8: </span> { |
1 |
<span class="lnum"> 9: </span> var builder = <span class="kwrd">new</span> ConfigurationSourceBuilder(); |
1 |
<span class="lnum"> 10: </span> |
1 |
<span class="lnum"> 11: </span> builder.ConfigureInstrumentation() |
1 |
<span class="lnum"> 12: </span> .ForApplicationInstance(<span class="str">"MyApp"</span>) |
1 |
<span class="lnum"> 13: </span> .EnableLogging() |
1 |
<span class="lnum"> 14: </span> .EnablePerformanceCounters(); |
1 |
<span class="lnum"> 15: </span> |
1 |
<span class="lnum"> 16: </span> <span class="rem">//a single exception handling policy named MyPolicy for exceptions of type ArgumentNullException. </span> |
1 |
<span class="lnum"> 17: </span> <span class="rem">//The handler for this exception policy will log the exception to the General category (defined in the Logging Application Block configuration) </span> |
1 |
<span class="lnum"> 18: </span> <span class="rem">//as a warning with event ID 9000, wrap the ArgumentNullException with an InvalidOperationException, set the new exception message to MyMessage, and then re-throw the exception.</span> |
1 |
<span class="lnum"> 19: </span> builder.ConfigureExceptionHandling() |
1 |
<span class="lnum"> 20: </span> .GivenPolicyWithName(<span class="str">"MyPolicy"</span>) |
1 |
<span class="lnum"> 21: </span> .ForExceptionType<ArgumentNullException>() |
1 |
<span class="lnum"> 22: </span> .LogToCategory(<span class="str">"Exception"</span>) |
1 |
<span class="lnum"> 23: </span> .WithSeverity(System.Diagnostics.TraceEventType.Warning) |
1 |
<span class="lnum"> 24: </span> .UsingEventId(9000) |
1 |
<span class="lnum"> 25: </span> .WrapWith<InvalidOperationException>() |
1 |
<span class="lnum"> 26: </span> .UsingMessage(<span class="str">"MyMessage"</span>) |
1 |
<span class="lnum"> 27: </span> .ThenNotifyRethrow(); |
1 |
<span class="lnum"> 28: </span> |
1 |
<span class="lnum"> 29: </span> <span class="rem">//logging application </span> |
1 |
<span class="lnum"> 30: </span> builder.ConfigureLogging() |
1 |
<span class="lnum"> 31: </span> .WithOptions |
1 |
<span class="lnum"> 32: </span> .DoNotRevertImpersonation() |
1 |
<span class="lnum"> 33: </span> .LogToCategoryNamed(<span class="str">"Exception"</span>) |
1 |
<span class="lnum"> 34: </span> .SendTo.FlatFile(<span class="str">"Exception Logging File"</span>) |
1 |
<span class="lnum"> 35: </span> .FormatWith(<span class="kwrd">new</span> FormatterBuilder() |
1 |
<span class="lnum"> 36: </span> .TextFormatterNamed(<span class="str">"Text Formatter"</span>) |
1 |
<span class="lnum"> 37: </span> . UsingTemplate(<span class="str">"Timestamp: {timestamp}{newline}Message: {message}{newline}Category: {category}{newline}"</span>)) |
1 |
<span class="lnum"> 38: </span> .ToFile(<span class="str">"d:\\logs\\ExceptionsLog.log"</span>) |
1 |
<span class="lnum"> 39: </span> .SendTo.RollingFile(<span class="str">"Rolling Log files"</span>) |
1 |
<span class="lnum"> 40: </span> .RollAfterSize(1024) |
1 |
<span class="lnum"> 41: </span> .ToFile(<span class="str">"d:\\logs\\Rollinglog.log"</span>) |
1 |
<span class="lnum"> 42: </span> .LogToCategoryNamed(<span class="str">"General"</span>) |
1 |
<span class="lnum"> 43: </span> .WithOptions.SetAsDefaultCategory() |
1 |
<span class="lnum"> 44: </span> .SendTo.SharedListenerNamed(<span class="str">"Exception Logging File"</span>); |
1 |
<span class="lnum"> 45: </span> |
1 |
<span class="lnum"> 46: </span> var configSource = <span class="kwrd">new</span> DictionaryConfigurationSource(); |
1 |
<span class="lnum"> 47: </span> builder.UpdateConfigurationWithReplace(configSource); |
1 |
<span class="lnum"> 48: </span> EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); |
1 |
<span class="lnum"> 49: </span> |
1 |
<span class="lnum"> 50: </span> var ex = HttpContext.Current.Server.GetLastError(); |
1 |
<span class="lnum"> 51: </span> var em = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>(); |
1 |
<span class="lnum"> 52: </span> em.HandleException(ex.InnerException, <span class="str">"MyPolicy"</span>); |
1 |
<span class="lnum"> 53: </span> } |
注意上面的代码, 为了运行代码您需要引用以下程序集
Enterprise Library Share Common Library
Microsoft.Practices.ServiceLocation
Logging Application Block
Exception Handling Application Block
Exception Handling Logging Provider
这里我们使用Fluent API配置, 因此没有配置XML文件. 所以不需要Web.Config中配置任何信息. 代码中有注释. 为了测试我们使用一个PAGE故意Throw 一个ArgumentNullException. 通过Server.GetLastError()获取Exception, 这时由名为MyPolicy策略处理异常. 对于ArgumentNullException把它们记录日志到名为Exception分类中,这个日志文件位于d:\\logs\\
ExceptionLog.log.实际开发你完全按照你的需要来自定义策略.
然后这个日志文件中写出的内容是这样的:
1 |
----------------------------------------Timestamp: 2011-11-12 5:57:08Message: HandlingInstanceID: a99d005d-5f8d-4613-9522-2d60efb089aaAn exception of type <span class="str">'System.ArgumentNullException'</span> occurred and was caught.----------------------------------------------------------------------------11/12/2011 13:57:08Type : System.ArgumentNullException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Message : Value cannot be <span class="kwrd">null</span>.Parameter name: Demo errorSource : MyWebHelp link : ParamName : Demo errorData : System.Collections.ListDictionaryInternalTargetSite : Void Page_Load(System.Object, System.EventArgs)Stack Trace : at MyWeb.About.Page_Load(Object sender, EventArgs e) <span class="kwrd">in</span> H:\My Project\DotNet40\TDD2010\WebHost\MyWeb\About.aspx.cs:line 14 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)Additional Info:MachineName : USERTimeStamp : 2011-11-12 5:57:08FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35AppDomainName : 3e5cb21e-3-129655510216406250ThreadIdentity : WindowsIdentity : USER\PetterCategory: Exception |
由于我们日志模块我们配置还需要写Rollinglog.log文件,内容如下:
1 |
----------------------------------------Exception Warning: 9000 : Timestamp: 2011-11-12 5:57:08Message: HandlingInstanceID: a99d005d-5f8d-4613-9522-2d60efb089aaAn exception of type <span class="str">'System.ArgumentNullException'</span> occurred and was caught.----------------------------------------------------------------------------11/12/2011 13:57:08Type : System.ArgumentNullException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Message : Value cannot be <span class="kwrd">null</span>.Parameter name: Demo errorSource : MyWebHelp link : ParamName : Demo errorData : System.Collections.ListDictionaryInternalTargetSite : Void Page_Load(System.Object, System.EventArgs)Stack Trace : at MyWeb.About.Page_Load(Object sender, EventArgs e) <span class="kwrd">in</span> H:\My Project\DotNet40\TDD2010\WebHost\MyWeb\About.aspx.cs:line 14 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)Additional Info:MachineName : USERTimeStamp : 2011-11-12 5:57:08FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35AppDomainName : 3e5cb21e-3-129655510216406250ThreadIdentity : WindowsIdentity : USER\PetterCategory: ExceptionPriority: 0EventId: 9000Severity: WarningTitle:Enterprise Library Exception HandlingMachine: USERApp Domain: 3e5cb21e-3-129655510216406250ProcessId: 2444Process Name: C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\WebDev.WebServer40.exeThread Name: Win32 ThreadId:2748Extended Properties: ---------------------------------------- |
1 |
你可以看到上面的EventId=9000与我们之前在CODE中配置是相同的. <br /> |
1 |
在开源社区有一个组件<a href="http://code.google.com/p/elmah/" target="_blank">ELMAH</a>(Error Logging Modules and Handlers for ASP.NET),已实现Error处理发邮件,写DB,发送到SNS等功能. 我们随意来看下它的代码:<br />它就是基于IHttpModule的扩展,下面代码来ELMAH: |
1 |
<span class="lnum"> 1: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 2: </span> <span class="rem">/// Provides an abstract base class for <see cref="IHttpModule"/> that</span> |
1 |
<span class="lnum"> 3: </span> <span class="rem">/// supports discovery from within partial trust environments.</span> |
1 |
<span class="lnum"> 4: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 5: </span> <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> HttpModuleBase : IHttpModule |
1 |
<span class="lnum"> 6: </span> { |
1 |
<span class="lnum"> 7: </span> <span class="kwrd">void</span> IHttpModule.Init(HttpApplication context) |
1 |
<span class="lnum"> 8: </span> { |
1 |
<span class="lnum"> 9: </span> <span class="kwrd">if</span> (context == <span class="kwrd">null</span>) |
1 |
<span class="lnum"> 10: </span> <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentNullException(<span class="str">"context"</span>); |
1 |
<span class="lnum"> 11: </span> |
1 |
<span class="lnum"> 12: </span> <span class="kwrd">if</span> (SupportDiscoverability) |
1 |
<span class="lnum"> 13: </span> HttpModuleRegistry.RegisterInPartialTrust(context, <span class="kwrd">this</span>); |
1 |
<span class="lnum"> 14: </span> |
1 |
<span class="lnum"> 15: </span> OnInit(context); |
1 |
<span class="lnum"> 16: </span> } |
1 |
<span class="lnum"> 17: </span> |
1 |
<span class="lnum"> 18: </span> <span class="kwrd">void</span> IHttpModule.Dispose() |
1 |
<span class="lnum"> 19: </span> { |
1 |
<span class="lnum"> 20: </span> OnDispose(); |
1 |
<span class="lnum"> 21: </span> } |
1 |
<span class="lnum"> 22: </span> |
1 |
<span class="lnum"> 23: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 24: </span> <span class="rem">/// Determines whether the module will be registered for discovery</span> |
1 |
<span class="lnum"> 25: </span> <span class="rem">/// in partial trust environments or not.</span> |
1 |
<span class="lnum"> 26: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 27: </span> <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">bool</span> SupportDiscoverability |
1 |
<span class="lnum"> 28: </span> { |
1 |
<span class="lnum"> 29: </span> get { <span class="kwrd">return</span> <span class="kwrd">false</span>; } |
1 |
<span class="lnum"> 30: </span> } |
1 |
<span class="lnum"> 31: </span> |
1 |
<span class="lnum"> 32: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 33: </span> <span class="rem">/// Initializes the module and prepares it to handle requests.</span> |
1 |
<span class="lnum"> 34: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 35: </span> <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> OnInit(HttpApplication application) {} |
1 |
<span class="lnum"> 36: </span> |
1 |
<span class="lnum"> 37: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 38: </span> <span class="rem">/// Disposes of the resources (other than memory) used by the module.</span> |
1 |
<span class="lnum"> 39: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 40: </span> <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> OnDispose() {} |
1 |
<span class="lnum"> 41: </span> } |
1 |
这是ErrorLogModule实现之前HttpModuleBase: |
1 |
<span class="lnum"> 1: </span><span class="kwrd">public</span> <span class="kwrd">class</span> ErrorLogModule : HttpModuleBase, IExceptionFiltering |
1 |
<span class="lnum"> 2: </span> { |
1 |
<span class="lnum"> 3: </span> <span class="kwrd">public</span> <span class="kwrd">event</span> ExceptionFilterEventHandler Filtering; |
1 |
<span class="lnum"> 4: </span> <span class="kwrd">public</span> <span class="kwrd">event</span> ErrorLoggedEventHandler Logged; |
1 |
<span class="lnum"> 5: </span> |
1 |
<span class="lnum"> 6: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 7: </span> <span class="rem">/// Initializes the module and prepares it to handle requests.</span> |
1 |
<span class="lnum"> 8: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 9: </span> |
1 |
<span class="lnum"> 10: </span> <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnInit(HttpApplication application) |
1 |
<span class="lnum"> 11: </span> { |
1 |
<span class="lnum"> 12: </span> <span class="kwrd">if</span> (application == <span class="kwrd">null</span>) |
1 |
<span class="lnum"> 13: </span> <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentNullException(<span class="str">"application"</span>); |
1 |
<span class="lnum"> 14: </span> |
1 |
<span class="lnum"> 15: </span> application.Error += <span class="kwrd">new</span> EventHandler(OnError); |
1 |
<span class="lnum"> 16: </span> ErrorSignal.Get(application).Raised += <span class="kwrd">new</span> ErrorSignalEventHandler(OnErrorSignaled); |
1 |
<span class="lnum"> 17: </span> } |
1 |
<span class="lnum"> 18: </span> |
1 |
<span class="lnum"> 19: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 20: </span> <span class="rem">/// Gets the <see cref="ErrorLog"/> instance to which the module</span> |
1 |
<span class="lnum"> 21: </span> <span class="rem">/// will log exceptions.</span> |
1 |
<span class="lnum"> 22: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 23: </span> <span class="kwrd">protected</span> <span class="kwrd">virtual</span> ErrorLog GetErrorLog(HttpContext context) |
1 |
<span class="lnum"> 24: </span> { |
1 |
<span class="lnum"> 25: </span> <span class="kwrd">return</span> ErrorLog.GetDefault(context); |
1 |
<span class="lnum"> 26: </span> } |
1 |
<span class="lnum"> 27: </span> |
1 |
<span class="lnum"> 28: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 29: </span> <span class="rem">/// The handler called when an unhandled exception bubbles up to </span> |
1 |
<span class="lnum"> 30: </span> <span class="rem">/// the module.</span> |
1 |
<span class="lnum"> 31: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 32: </span> <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> OnError(<span class="kwrd">object</span> sender, EventArgs args) |
1 |
<span class="lnum"> 33: </span> { |
1 |
<span class="lnum"> 34: </span> HttpApplication application = (HttpApplication) sender; |
1 |
<span class="lnum"> 35: </span> LogException(application.Server.GetLastError(), application.Context); |
1 |
<span class="lnum"> 36: </span> } |
1 |
<span class="lnum"> 37: </span> |
1 |
<span class="lnum"> 38: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 39: </span> <span class="rem">/// The handler called when an exception is explicitly signaled.</span> |
1 |
<span class="lnum"> 40: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 41: </span> <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> OnErrorSignaled(<span class="kwrd">object</span> sender, ErrorSignalEventArgs args) |
1 |
<span class="lnum"> 42: </span> { |
1 |
<span class="lnum"> 43: </span> LogException(args.Exception, args.Context); |
1 |
<span class="lnum"> 44: </span> } |
1 |
<span class="lnum"> 45: </span> |
1 |
<span class="lnum"> 46: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 47: </span> <span class="rem">/// Logs an exception and its context to the error log.</span> |
1 |
<span class="lnum"> 48: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 49: </span> <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> LogException(Exception e, HttpContext context) |
1 |
<span class="lnum"> 50: </span> { |
1 |
<span class="lnum"> 51: </span> <span class="kwrd">if</span> (e == <span class="kwrd">null</span>) |
1 |
<span class="lnum"> 52: </span> <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentNullException(<span class="str">"e"</span>); |
1 |
<span class="lnum"> 53: </span> |
1 |
<span class="lnum"> 54: </span> <span class="rem">//</span> |
1 |
<span class="lnum"> 55: </span> <span class="rem">// Fire an event to check if listeners want to filter out</span> |
1 |
<span class="lnum"> 56: </span> <span class="rem">// logging of the uncaught exception.</span> |
1 |
<span class="lnum"> 57: </span> <span class="rem">//</span> |
1 |
<span class="lnum"> 58: </span> |
1 |
<span class="lnum"> 59: </span> ExceptionFilterEventArgs args = <span class="kwrd">new</span> ExceptionFilterEventArgs(e, context); |
1 |
<span class="lnum"> 60: </span> OnFiltering(args); |
1 |
<span class="lnum"> 61: </span> |
1 |
<span class="lnum"> 62: </span> <span class="kwrd">if</span> (args.Dismissed) |
1 |
<span class="lnum"> 63: </span> <span class="kwrd">return</span>; |
1 |
<span class="lnum"> 64: </span> |
1 |
<span class="lnum"> 65: </span> <span class="rem">//</span> |
1 |
<span class="lnum"> 66: </span> <span class="rem">// Log away...</span> |
1 |
<span class="lnum"> 67: </span> <span class="rem">//</span> |
1 |
<span class="lnum"> 68: </span> |
1 |
<span class="lnum"> 69: </span> ErrorLogEntry entry = <span class="kwrd">null</span>; |
1 |
<span class="lnum"> 70: </span> |
1 |
<span class="lnum"> 71: </span> <span class="kwrd">try</span> |
1 |
<span class="lnum"> 72: </span> { |
1 |
<span class="lnum"> 73: </span> Error error = <span class="kwrd">new</span> Error(e, context); |
1 |
<span class="lnum"> 74: </span> ErrorLog log = GetErrorLog(context); |
1 |
<span class="lnum"> 75: </span> <span class="kwrd">string</span> id = log.Log(error); |
1 |
<span class="lnum"> 76: </span> entry = <span class="kwrd">new</span> ErrorLogEntry(log, id, error); |
1 |
<span class="lnum"> 77: </span> } |
1 |
<span class="lnum"> 78: </span> <span class="kwrd">catch</span> (Exception localException) |
1 |
<span class="lnum"> 79: </span> { |
1 |
<span class="lnum"> 80: </span> <span class="rem">//</span> |
1 |
<span class="lnum"> 81: </span> <span class="rem">// IMPORTANT! We swallow any exception raised during the </span> |
1 |
<span class="lnum"> 82: </span> <span class="rem">// logging and send them out to the trace . The idea </span> |
1 |
<span class="lnum"> 83: </span> <span class="rem">// here is that logging of exceptions by itself should not </span> |
1 |
<span class="lnum"> 84: </span> <span class="rem">// be critical to the overall operation of the application.</span> |
1 |
<span class="lnum"> 85: </span> <span class="rem">// The bad thing is that we catch ANY kind of exception, </span> |
1 |
<span class="lnum"> 86: </span> <span class="rem">// even system ones and potentially let them slip by.</span> |
1 |
<span class="lnum"> 87: </span> <span class="rem">//</span> |
1 |
<span class="lnum"> 88: </span> |
1 |
<span class="lnum"> 89: </span> Trace.WriteLine(localException); |
1 |
<span class="lnum"> 90: </span> } |
1 |
<span class="lnum"> 91: </span> |
1 |
<span class="lnum"> 92: </span> <span class="kwrd">if</span> (entry != <span class="kwrd">null</span>) |
1 |
<span class="lnum"> 93: </span> OnLogged(<span class="kwrd">new</span> ErrorLoggedEventArgs(entry)); |
1 |
<span class="lnum"> 94: </span> } |
1 |
<span class="lnum"> 95: </span> |
1 |
<span class="lnum"> 96: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 97: </span> <span class="rem">/// Raises the <see cref="Logged"/> event.</span> |
1 |
<span class="lnum"> 98: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 99: </span> <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> OnLogged(ErrorLoggedEventArgs args) |
1 |
<span class="lnum"> 100: </span> { |
1 |
<span class="lnum"> 101: </span> ErrorLoggedEventHandler handler = Logged; |
1 |
<span class="lnum"> 102: </span> |
1 |
<span class="lnum"> 103: </span> <span class="kwrd">if</span> (handler != <span class="kwrd">null</span>) |
1 |
<span class="lnum"> 104: </span> handler(<span class="kwrd">this</span>, args); |
1 |
<span class="lnum"> 105: </span> } |
1 |
<span class="lnum"> 106: </span> |
1 |
<span class="lnum"> 107: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 108: </span> <span class="rem">/// Raises the <see cref="Filtering"/> event.</span> |
1 |
<span class="lnum"> 109: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 110: </span> <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> OnFiltering(ExceptionFilterEventArgs args) |
1 |
<span class="lnum"> 111: </span> { |
1 |
<span class="lnum"> 112: </span> ExceptionFilterEventHandler handler = Filtering; |
1 |
<span class="lnum"> 113: </span> |
1 |
<span class="lnum"> 114: </span> <span class="kwrd">if</span> (handler != <span class="kwrd">null</span>) |
1 |
<span class="lnum"> 115: </span> handler(<span class="kwrd">this</span>, args); |
1 |
<span class="lnum"> 116: </span> } |
1 |
<span class="lnum"> 117: </span> |
1 |
<span class="lnum"> 118: </span> <span class="rem">/// <summary></span> |
1 |
<span class="lnum"> 119: </span> <span class="rem">/// Determines whether the module will be registered for discovery</span> |
1 |
<span class="lnum"> 120: </span> <span class="rem">/// in partial trust environments or not.</span> |
1 |
<span class="lnum"> 121: </span> <span class="rem">/// </summary></span> |
1 |
<span class="lnum"> 122: </span> <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">bool</span> SupportDiscoverability |
1 |
<span class="lnum"> 123: </span> { |
1 |
<span class="lnum"> 124: </span> get { <span class="kwrd">return</span> <span class="kwrd">true</span>; } |
1 |
<span class="lnum"> 125: </span> } |
1 |
<span class="lnum"> 126: </span> } |
1 |
更多的功能等待您去挖掘,我们在实际开发中按需选择.希望这篇POST对您开发有帮助.<br /> |
转自:http://www.cnblogs.com/wintersun/archive/2011/11/12/2246513.html