29 June 2004

OnError and [Page]_Error

Aspx Page have two event methods: [Page]_Error and OnError. They are different. OnError hands control to a private HandleError method. HandleError checks whether web.config:customErrors is turned on and redirects request accordingly.
The base implementation on OnError: checks whether tracing is turned on and adds its own bit about the exception just raised. The main reason to override OnError is to replace this behavior with your own implementation. There is no good reason to put other code there. If <customErrors> turned on, code in OnError will fire first then redirect request to customized error page. In this case code in Page_Error will not fire, as OnError fires first.
To do error-handling at the Page level, use Page_Error.

Experiment
Create an aspx page ManMadeError with both event handling methods:


private void ManMadeError_Error(object sender, System.EventArgs e)
{
Exception ex = Server.GetLastError();
// System.Diagnostics.Trace.WriteLine(ex.ToString(), "Error");
if (Trace.IsEnabled)
Response.Write("Trace on");

Trace.Warn("Error",ex.ToString());
Session["Error"] = ex;
Server.ClearError();
Server.Transfer("500.aspx");
}
protected override void OnError(EventArgs e)
{
Response.Write("<h1> We have a problem </H1>");
}

in Web.config, we have

<customErrors mode="On" defaultRedirect="./Errors/500.aspx" >
<error statusCode="401" redirect="./Chp8Security/Authen_2.aspx" />
<error statusCode="500" redirect="./Errors/500.aspx" />
<error statusCode="404" redirect="./Errors/404.aspx" />
</customErrors>

Fires the exception, and watch the implantation in ManMadeError_Error is ignored entirely.

No comments: