近期维护一些老项目,是用webform写的,发现没有记日志,对异常处理也没有统一管理所以先加一个全局异常处理
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<add name="errorCatchModule" type="SupplierPortal.Common.ModulesHandlerHelper, SupplierPortal" />
</modules>
</system.webServer>
一开始出现了问题是对这个配置不熟
先解释一下<modules runAllManagedModulesForAllRequests="true">
<add name="errorCatchModule" type="SupplierPortal.Common.ModulesHandlerHelper, SupplierPortal" />
</modules>
主要是这句
add后面的name是你自己定义的随便一个名字,type 是关键逗号以前是你写的类, 逗号以后是dll的名称如果不知道可以看看生产后的bin里面dll是啥
之后就是写 全局异常类了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SupplierPortal.Common
{
public class ModulesHandlerHelper : IHttpModule
{
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();
Log log = LogFactory.GetLogger("ModulesHandlerHelper");
log.Error(ex);
//实际发生的异常
Exception iex = ex.InnerException;
response.Write("<script>window.location.href='../Pages/ErrorMessagePage.aspx'</script>");
//response.Write("来自ErrorModule的错误处理<br />");
//response.Write(iex.Message);
ctx.Server.ClearError();
}
public void Dispose() { }
}
}