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的实现,显得不够灵活和通用。