Search code examples
c#asp.neterror-handlingwebformshttp-error

ASP.net catch error on error page


I have set up my custom error page which work fine:

<customErrors mode="On"  redirectMode="ResponseRewrite">
  <error statusCode="500" redirect="~/Pages/ErrorPages/500.aspx" />
</customErrors>

On 500.aspx:

    Response.ClearContent();
    Response.StatusCode = 500;
    Exception = Server.GetLastError();
    Code.Errors.Error.RecordNewError(ErrorType.InternalException, Exception, Code.Common.GetUserIPAddress().ToString(), HttpContext.Current);
    Server.ClearError();

Problem is, if the error page throws an error itself we get an ugly error:

Runtime Error

Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.

How do I fall back to a more basic custom error page if the error page itself throws an error?


Solution

  • Figured it out just now! Use the Page_Error method on the error pages themselves:

        private void Page_Error(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.StatusCode = 500;
            Exception = Server.GetLastError();
            HttpContext.Current.Response.Write("Error");
            HttpContext.Current.Response.End();
        }