您的位置:首页 > 编程语言 > ASP

asp.net捕获全局未处理异常的几种方法

2012-04-25 15:54 671 查看

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: