如果您只需要重定向,最好使用web.config custom error pages
. 但是,如果您还想做一些更多的事情,例如比您需要使用的日志记录,请执行HttpModule
以下操作:
public class ErrorManagementModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
//handle context exceptions
context.Error += (sender, e) => HandleError();
//handle page exceptions
context.PostMapRequestHandler += (sender, e) =>
{
Page page = HttpContext.Current.Handler as Page;
if (page != null)
page.Error += (_sender, _e) => HandleError();
};
}
private void HandleError()
{
Exception ex = HttpContext.Current.Server.GetLastError();
if (ex == null) return;
LogException(ex);
HttpException httpEx = ex as HttpException;
if (httpEx != null && httpEx.GetHttpCode() == 500)
{
HttpContext.Current.Response.Redirect("/PrettyErrorPage.aspx", true);
}
}
}