如何在。net中捕捉全局未处理异常

  介绍

这篇文章将为大家详细讲解有关如何在。net中捕捉全局未处理异常,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

<强>方式一,Page_Error处理页面级未处理异常

作用域:当前的。aspx页面

描述:在需要处理的aspx页面的cs文件中,实现Page_Error方法,达到侦听当前页面未处理的异常

protected  void  Page_Error (object ,发送方,EventArgs  e)   {才能   ,,string  errorMsg =, String.Empty;   ,,Exception  currentError =, Server.GetLastError ();   ,,errorMsg  +=,“来自页面的异常处理& lt; br /祝辞;“;   ,,errorMsg  +=,“系统发生错误:& lt; br /祝辞;“;   ,,errorMsg  +=,“错误地址:“,+,Request.Url  +,“& lt; br /祝辞;“;   ,,errorMsg  +=,“错误信息:“,+,currentError.Message  +,“& lt; br /祝辞;“;   ,,Response.Write (errorMsg);   ,,Server.ClearError();//清除异常(否则将引发全局的Application_Error事件)   以前,,}

<强>方式二,通过step来捕获未处理的异常

作用域:全局的请求请求

描述:通过一个类实现IHttpModule接口,并侦听未经处理的异常

实现步骤:

1,首先需要新建一个类(MyHttpModule),该类需实现IHttpModule接口,具体代码实例如下:

///, & lt; summary>   ,///MyHttpModule   ,///& lt;/summary>   ,public  class  MyHttpModules : IHttpModule   ,{   public  void  Init (HttpApplication 上下文)   {才能   ,,context.Error  +=, new  EventHandler (context_Error);   ,,}      public 才能;void  context_Error (object ,发送方,EventArgs  e)   {才能   ,,//此处处理异常   ,,HttpContext  ctx =, HttpContext.Current;   ,,HttpResponse  response =, ctx.Response;   ,,HttpRequest  request =, ctx.Request;      ,,//获取到HttpUnhandledException异常,这个异常包含一个实际出现的异常   ,,Exception  ex =, ctx.Server.GetLastError ();   ,,//实际发生的异常   ,,Exception  iex =, ex.InnerException;      ,,response.Write(“来自ErrorModule的错误处理& lt; br /在“);   ,,response.Write (iex.Message);      ,,ctx.Server.ClearError ();   ,,}   }

2,配置文件配置相应的step 4节点

配置文件配置step 4节点时,有以下两种方式(根据IIS版本而异)

方法,当IIS版本为7.0以下时,在& lt; system.web>中新增如下配置节点

& lt; httpModules>   & lt; add  name=癕yHttpModule",类型=癕yHttpModule.MyHttpModules, MyHttpModule",/比;   & lt;/httpModules>

方法2,当IIS版本为7.0及其以上版本时,在& lt; system.webServer>中新增如下配置节点

& lt; modules>   & lt; add  name=癕yHttpModule",类型=癕yHttpModule.MyHttpModules, MyHttpModule"/比;   & lt;/modules>

<强>方式三,通过全球中捕获未处理的异常

作用域:全局的请求请求

描述:通过在全球中实现Application_Error方法,来达到侦听未经处理的异常

具体代码如下:

void  Application_Error (object ,发送方,EventArgs  e)   {才能   ,,//获取到HttpUnhandledException异常,这个异常包含一个实际出现的异常   ,,Exception  ex =, Server.GetLastError ();   ,,//实际发生的异常   ,,Exception  iex =, ex.InnerException;      ,,string  errorMsg =, String.Empty;   ,,string  particular =, String.Empty;   ,,if  (iex  !=, null)   ,,{   ,,,errorMsg =, iex.Message;   ,,,particular =, iex.StackTrace;   ,,}   其他的,,   ,,{   ,,,errorMsg =, ex.Message;   ,,,particular =, ex.StackTrace;   ,,}   ,,HttpContext.Current.Response.Write(“来自全球的错误处理& lt; br /在“);   ,,HttpContext.Current.Response.Write (errorMsg);      ,,Server.ClearError();//处理完及时清理异常   null

如何在。net中捕捉全局未处理异常