Redirect to error page

10,766

Solution 1

Instead of Response.Redirect, which sends a response to the client asking it to request a different page, you should call Server.Transfer, which runs a different page immediately and sends that page directly to the client.

You can then put the exception in HttpContext.Items and read it from HttpContext.Items in your error page.

For example:

catch (Exception ex) {
    HttpContext.Current.Items.Add("Exception", ex);
    Server.Transfer("Error.aspx");
}

In Error.aspx, you can then get the exception like this:

<% 
    Exception error;
    if (!HttpContext.Current.Items.Contains("Exception"))
       Response.Redirect("/");  //There was no error; the user typed Error.aspx into the browser
    error = (Exception)HttpContext.Current.Items["Exception"];
%>

Solution 2

Yes that would work (with some semicolons added of course and you probably just want to send the exception message):

String URL = "Page2.aspx?Exception=" + ex.Message;
Response.Redirect(URL);
Share:
10,766
anay
Author by

anay

Updated on June 17, 2022

Comments

  • anay
    anay almost 2 years

    I want to use Response.Redirect to redirect the browser when an exception occurs.
    I also want to pass the exception message to my error page.

    For example:

    string URL = "Page2.aspx?Exception=" + ex.ToString()
    Response.Redirect(URL)
    

    Can it be done? Is this the right syntax?