asp.net捕获全局未处理异常的几种方法
1.通过HttpModule来捕获未处理的异常【推荐】
首先需要定义一个HttpModule,并监听未处理异常,代码如下:
public void Init(HttpApplication context) { context.Error += new EventHandler(context_Error); } public void context_Error(object sender, 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的错误处理<br />"); response.Write(iex.Message); ctx.Server.ClearError(); }
然后在web.config中加入配置信息:
<httpModules> <add name="errorCatchModule" type="WebModules.ErrorHandlerModule, WebModules" /> </httpModules>
这样就可以处理来自webApp中未处理的异常信息了。
之所以推荐这种方法,是因为这种实现易于扩展、通用;这种方法也是用的最多的。
2.Global中捕获未处理的异常
在Global.asax中有一个Application_Error的方法,这个方法是在应用程序发生未处理异常时调用的,我们可以在这里添加处理代码:
void Application_Error(object sender, 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; } else { errorMsg = ex.Message; particular = ex.StackTrace; } HttpContext.Current.Response.Write("来自Global的错误处理<br />"); HttpContext.Current.Response.Write(errorMsg); Server.ClearError();//处理完及时清理异常 }
这种处理方式同样能够获取全局未处理异常,但相对于使用HttpModule的实现,显得不够灵活和通用。
HttpModule优先于Global中的Application_Error方法。
3.页面级别的异常捕获
我们还可以在页面中添加异常处理方法:在页面代码中添加方法Page_Error,这个方法会处理页面上发生的未处理异常信息。
protected void Page_Error(object sender, EventArgs e) { string errorMsg = String.Empty; Exception currentError = Server.GetLastError(); errorMsg += "来自页面的异常处理<br />"; errorMsg += "系统发生错误:<br />"; errorMsg += "错误地址:" + Request.Url + "<br />"; errorMsg += "错误信息:" + currentError.Message + "<br />"; Response.Write(errorMsg); Server.ClearError();//清除异常(否则将引发全局的Application_Error事件) }
这种方法会优先于HttpModule和Global。
本文作者:拓荒者IT
本文链接:https://www.cnblogs.com/youring2/archive/2012/04/25/2469974.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
📌做了个微信公众号【拓荒者IT】,分享各种技术干货,新内容首发到公众号,欢迎关注❤️
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步